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

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

JS/jQuery:

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

Easy enough, until you’d wish to actually run a click event thereon #close button. Neither of those will actually work as you’d expect them to:

JS/jQuery:

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

JS/jQuery:

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


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:

$('#popup').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:

JS/jQuery:

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

SOLUTION

The solution is to connect the press event to the document, then pass the element you would like the action attached to along to the function using the subsequent method:

JS/jQuery:

$('#popup').append('<div id="close">Close</div>');
 
$(document).on('click', '#close', function() {
      // This will work!
});

Categorized in:

Tagged in:

, ,