This question already has an answer here:
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".
Any idea how I can fix this?
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.
Sometimes doing this (the top-voted answer) is not always enough:
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:
Because it is a function, whenever I set up my listener this way, I typically call it on document ready:
Then, whenever you add some dynamically added element, call that method again:
Hopefully this helps!
Regards,
You can bind a single click event to a page for all elements, no matter if they are already on that page or if they will arrive at some future time, like that:
Been using it for a while. Works like a charm.
In jQuery 1.7 and later, it is recommended to use
.on()
in place of bind or any other event delegation method, but.bind()
still works.If you're adding a pile of anchors to the DOM, look into event delegation instead.
Here's a simple example:
If your on jQuery 1.3+ then use .live()
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/
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...
You can write...
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:
As long as the ul tag exists this will work (no li elements need exist yet).
You want to use the
live()
function. See the docs.For example: