Adding event listeners to dynamically added elements using jQuery

JqueryEvents

Jquery Problem Overview


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?

Jquery Solutions


Solution 1 - Jquery

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
});

Solution 2 - Jquery

$(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.

Solution 3 - Jquery

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/

Solution 4 - Jquery

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWizView Question on Stackoverflow
Solution 1 - JqueryJackView Answer on Stackoverflow
Solution 2 - JqueryzerkmsView Answer on Stackoverflow
Solution 3 - JqueryLuc Kim-HallView Answer on Stackoverflow
Solution 4 - JqueryhaotangView Answer on Stackoverflow