111

So right now, I understand that in order to attach an event listener to a dynamically added element, you have to redefine the listener after adding the element.

Is there any way to bypass this, so you don't have to execute a whole extra block of code?

1

4 Answers 4

212

Using .on() you can define your function once, and it will execute for any dynamically added elements.

for example

$('#staticDiv').on('click', 'yourSelector', function() {
  //do something
});
Sign up to request clarification or add additional context in comments.

22 Comments

Is there a way to use .on() on events that are not in native jquery. i.e. I need to use it with a Jquery plugin.
@Wiz: you can bind to any event
@zerkms Well I'm trying to use it with Hovercard, and $('.class').on('hovercard', function(){}); is not working, when the usual syntax is $('.class').hovercard(function(){});
@Wiz Here's a very basic jsfiddle to get you started, you might want to make sure that nothing adverse happens when you call the plugin multiple times on an element. ( note I started the fiddle off of one of demos since I didn't see a cdn for the hovercard plugin)
@HPWD both will work, the document is above the body in the dom. There isn't really going to be much practical difference but in general you want to bind your handler to the closest element possible so it doesn't "bubble" up further then it needs to. I recommend you read up on event bubbling to get a better understanding.
|
50
$(document).on('click', 'selector', handler);

Where click is an event name, and handler is an event handler, like reference to a function or anonymous function function() {}

PS: if you know the particular node you're adding dynamic elements to - you could specify it instead of document.

2 Comments

Don't use $(document). The event should be bound to the closest static parent.
@Joseph Silber: I've added PS for that. And "don't use" is too much categorical. There are valid cases for using it (don't even mention it is specified in jquery documentation: api.jquery.com/live)
6

You are dynamically generating those elements so any listener applied on page load wont be available. I have edited your fiddle with the correct solution. Basically jQuery holds the event for later binding by attaching it to the parent Element and propagating it downward to the correct dynamically created element.

$('#musics').on('change', '#want',function(e) {
    $(this).closest('.from-group').val(($('#want').is(':checked')) ? "yes" : "no");
    var ans=$(this).val();
    console.log(($('#want').is(':checked')));
});

http://jsfiddle.net/swoogie/1rkhn7ek/39/

Comments

1

When adding new element with jquery plugin calls, you can do like the following:

$('<div>...</div>').hoverCard(function(){...}).appendTo(...)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.