As you may have discovered while trying to run a click() event on a jQuery-generated (appended) element, you can’t accomplish it using the standard jQuery method of attaching an event to an element.

For example, let’s say we append a button dynamically to another element using jQuery to control a particular user action, like closing/hiding something on the page:

$('#element').append('<div id="close">Close</div>');

Easy enough, until you’d like to actually run a click event on that #close button. Neither of these will actually work as you’d expect them to:

$('#close').click( function() {
      // This won't work...
});
$('#close').on('click', function() {
      // This won't work...
});

Solution

The solution is to attach the click event to the document, then pass the element you want the action attached to along to the function using the following method:

$('#element').append('<div id="close">Close</div>');

$(document).on('click', '#close', function() {
      // This will work!
});

Leave a Reply

Your email address will not be published. Required fields are marked *

Continue Reading