Categories
dhtml events javascript jquery

How do I attach events to dynamic HTML elements with jQuery? [duplicate]

611

Suppose I have some jQuery code that attaches an event handler to all elements with class .myclass.

For example:

$(function(){
    $(".myclass").click( function() {
        // do something
    });
});

And my HTML might be as follows:

<a class="myclass" href="#">test1</a>
<a class="myclass" href="#">test2</a>
<a class="myclass" href="#">test3</a>

That works with no problem.
However, consider if the .myclass elements were written to the page at some future time.

For example:

<a id="anchor1" href="#">create link dynamically</a>
<script type="text/javascript">
$(function(){
    $("#anchor1").click( function() {
        $("#anchor1").append('<a class="myclass" href="#">test4</a>');
    });
});
</script>

In this case, the test4 link is created when a user clicks on a#anchor1.

The test4 link does not have the click() handler associated with it, even though it has class="myclass".

Basically, I would like to write the click() handler once and have it apply to both content present at page load, and content brought in later via AJAX / DHTML. Any idea how I can fix this?

4

1030

I am adding a new answer to reflect changes in later jQuery releases. The .live() method is deprecated as of jQuery 1.7.

From http://api.jquery.com/live/

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().

For jQuery 1.7+ you can attach an event handler to a parent element using .on(), and pass the a selector combined with ‘myclass’ as an argument.

See http://api.jquery.com/on/

So instead of…

$(".myclass").click( function() {
    // do something
});

You can write…

$('body').on('click', 'a.myclass', function() {
    // do something
});

This will work for all a tags with ‘myclass’ in the body, whether already present or dynamically added later.

The body tag is used here as the example had no closer static surrounding tag, but any parent tag that exists when the .on method call occurs will work. For instance a ul tag for a list which will have dynamic elements added would look like this:

$('ul').on('click', 'li', function() {
    alert( $(this).text() );
});

As long as the ul tag exists this will work (no li elements need exist yet).

10

  • This otherwise brilliant solution seems to have a problem with HTML content living in a Fancybox. I’ve reverted to creating the handlers for that manually. I didn’t try iFrame Content yet, so the content of the fanyxbos is part of the body or in my case of the document variable.

    – user673046

    Aug 11, 2013 at 19:49


  • 6

    live() is deprecated and .on() came. But it is not clear that when I write $('selector').on('event', callback(){}) then it wont work. Need to write desired selector inside on(). $(document).on('event', 'selector', callback(){}) or, $('body').on('event', 'selector', callback(){})

    Dec 21, 2013 at 14:36


  • 4

    what about performance? is it the same as attaching events directly?

    – Juan

    Apr 29, 2014 at 19:38


  • Not work when <a> element have href address that set to http://????

    – Mostafa

    Jul 4, 2016 at 15:50

  • $('body').on('each', 'myclass', function() { // do something }); @Sean I tried to make something on “each” of a “class”, but it doesn’t work. What is wrong?

    – horse

    Sep 3, 2016 at 6:49


113

Sometimes doing this (the top-voted answer) is not always enough:

$('body').on('click', 'a.myclass', function() {
    // do something
});

This can be an issue because of the order event handlers are fired. If you find yourself doing this, but it is causing issues because of the order in which it is handled.. You can always wrap that into a function, that when called “refreshes” the listener.

For example:

function RefreshSomeEventListener() {
    // Remove handler from existing elements
    $("#wrapper .specific-selector").off(); 

    // Re-add event handler for all matching elements
    $("#wrapper .specific-selector").on("click", function() {
        // Handle event.
    }
}

Because it is a function, whenever I set up my listener this way, I typically call it on document ready:

$(document).ready(function() {
    // Other ready commands / code

    // Call our function to setup initial listening
    RefreshSomeEventListener();
});

Then, whenever you add some dynamically added element, call that method again:

function SomeMethodThatAddsElement() {
    // Some code / AJAX / whatever.. Adding element dynamically

    // Refresh our listener, so the new element is taken into account
    RefreshSomeEventListener();
}

Hopefully this helps!

Regards,

3

  • Thanks! Couldn’t get it to work with other answers, your solution worked like a charm, however if I call RefreshSomeEventListener() after adding dynamic element, my event is triggered twice

    Mar 23, 2015 at 0:04

  • 1

    @DKMudrechenko Likely this is because you’re not fully removing the event listeners from it.

    Apr 12, 2017 at 17:30

  • This works, and good explanation, too.

    – John Ruiz

    Feb 26, 2021 at 17:54

36

After jQuery 1.7 the preferred methods are .on() and .off()

Sean’s answer shows an example.

Now Deprecated:

Use the jQuery functions .live() and .die(). Available in
jQuery 1.3.x

From the docs:

To display each paragraph’s text in an
alert box whenever it is clicked:

$("p").live("click", function(){
  alert( $(this).text() );
});

Also, the livequery plugin does this and has support for more events.

3

  • What if my selector needs to be the parent of some other element? For example: $(“p”).parent(“.myclass”).live(“click”, … This doesn’t seem to work with live().

    Aug 31, 2009 at 21:58

  • You could try to incorporate that into a single query like $(“p:has(.myclass)”).live(“click”,…). Note: there are some cases where live doesn’t work for all events. Check out livequery plugin for support not offered by live.

    Sep 1, 2009 at 1:41

  • 1

    This is no longer the correct Answer. The .live() method is deprecated as of jQuery 1.7. Use .on() instead. Lets get the correct answer[stackoverflow.com/a/9331127/363701] some upvotes. Or @Matt – do you want to update your answer?

    Feb 17, 2012 at 15:47