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

19 thoughts on “Run a Click Event on an Appended Element

  1. Evans says:

    Let me just say you bro deserve a beer! Some people find solutions and won’t post them online but you have helped me after spending more than an hour trying to fix this annoying issue. Cheers!

  2. Nidhi Singh says:

    Thank you so much for posting this!! I found your article after spending what seemed life forever to figure this out. Thanks again!

  3. Yasir says:

    Man I had to find a solution for this and I did so for three days. Thanks, mate just thanks.

  4. LordRampantHump says:

    These comments a fake and this is not a good way to handle this!

    let new = $(”);

    new.click(function(){
    // this requires no id
    })

    $(‘#element’).append(new);

Leave a Reply

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

Continue Reading