Working with Events, part 2
read 22 commentsIn my last article, I described the common problem of events seemingly ceasing to work for new elements added to a document, whether by some form of ajax or by DOM modification. We examined one way to overcome the problem: Event Delegation. With event delegation, we bind the event handler to a containing element that remains in the DOM and then check for the target of the event.
Cloning Nodes
This time, we'll take a look at re-binding event handlers. But before we do, I should mention that, as of jQuery version 1.2, event handlers can be cloned along with elements. Consider this unordered list:
-
<ul id="list3" class="eventlist">
-
<li>plain</li>
-
<li class="special">special <button>I am special</button></li>
-
<li>plain</li>
-
</ul>
We can make a copy of <li class="special"> and insert it after the original, while at the same time retaining any event handlers that were attached within the original. The plain .clone() method doesn't work that way; instead, it just copies the element:
-
});
-
});
Try it:
- plain
- special
- plain
As you can see, the original button is able to keep creating new list items, but the buttons inside the "dynamically generated" list items can't create new ones.
To get the event handlers copied over as well, all we have to do is pass in true to the method's single argument:
Note: I've added .append(' I\'m a clone!') here only as visual reinforcement of what is going on.
Try it now:
- plain
- special
- plain
Using .clone(true) is great when we want to make a copy of existing elements and their event handlers, but there are plenty of other situations that don't involve cloning in which we might want event handlers to persist.
Re-binding Basics
The basic concept behind re-binding is fairly straightforward: We create a function that binds the handlers and then call it whenever new elements are introduced. For example, with our unordered list above, we first create a function called addItem that registers the click handler, which in turn will add a new item:
Next, we call that function when the DOM initially loads:
-
addItem();
-
});
Finally, we can call the function inside the click handler—and inside itself. That way, it will bind the event handlers to the new list item as well.
We'll add one more click handler to the button, but this one will not be re-bound, so that we can see the difference.
Here is what the code for buttons in #list5 looks like, all together:
-
function addItem() {
-
var $newLi = $('<li class="special">special and new <button>I am new</button></li>');
-
addItem();
-
});
-
}
-
-
addItem();
-
-
// non-rebinding click handler ...
-
});
-
});
Try this one out:
- plain
- special
- plain
We can see that "pressed" is appended to the first list item each time it is clicked, but it is not appended to any of the list items created by our clicks. On the other hand, the created buttons are able to generate further list items because that function is being rebound.
However, what we've just done produces unwelcome results if we click on a button more than once. The click handler is bound again with each click of a button, producing a multiplier effect. The first click of a button creates one extra list item; the second creates two; the third, four; and so on.
Unbind, then Bind
To avoid the multiple binding, we can unbind first and then re-bind. So in line 2, instead of this ...
$('#list5 li.special button').click(function() {
... we'll have this ...
$('#list6 li.special button').unbind('click').bind('click', function() {
Note the use of .bind() here. This is the universal event binder that jQuery uses. All the others, such as .click(), .blur(), .resize(), and so on, are shorthand methods for their .bind('event') equivalent.
The complete new code, again with the additional non-rebinding click handler for contrast, looks like this:
-
function addItemUnbind() {
-
$('#list6 li.special button')
-
var $newLi = $('<li class="special">special and new <button>I am new</button></li>');
-
addItemUnbind();
-
});
-
}
-
addItemUnbind();
-
-
// non-rebinding click handler
-
});
-
});
See how this one works:
- plain
- special
- plain
Unfortunately, our attempt to unbind the addItemUnbind() function went too far, unbinding the "non-rebinding" click handler as well, before it even had a chance to run once (it's evident because there is no "pressed" text after the "I am special" button here). Clearly, we're going to have to be more careful about what we're unbinding.
Event Namespacing
One way to avoid the over-reaching event unbinding is to apply a "namespace" to the click event for both binding and unbinding. So, instead of .bind('click') and .unbind('click), we'll have, for example, .bind('click.addit') and .unbind('click.addit). Here is one last code sample, which looks identical to the previous, except that it now has the namespaced event (and the list id is list7):
-
function addItemNS() {
-
$('#list7 li.special button')
-
var $newLi = $('<li class="special">special and new <button>I am new</button></li>');
-
addItemNS();
-
});
-
}
-
addItemNS();
-
-
// non-rebinding click handler
-
});
-
});
We should now — finally! — have a set of behaviors attached to these buttons that act the way we intend them to:
- plain
- special
- plain
For more information about event namespacing, read Brandon Aaron's article, Namespace Your Events.
Bonus: Unbind by Function Reference
If you've made it this far, then you must have extraordinary patience, in which case I'll reward it with one final method of rebinding. Rather than namespace the events, we can reference the function in the second argument of the .bind() and .unbind() methods. We have to shuffle things around a bit to avoid "too much recursion," but it'll do just fine like so:
-
function addItemFinal() {
-
var $newLi = $('<li class="special">special and new <button>I am new</button></li>');
-
$('#list8 li.special button')
-
}
-
-
-
// non-rebinding click handler
-
});
-
});
Note here that there are no parentheses after "addItemFinal" when it appears inside the bind/unbind, because we are referencing the function, not calling it. So let's test it out one last time:
- plain
- special
- plain
Plugin Options
There are three great plugins that can do a lot of this work for us:
- Live Query by Brandon Aaron
- Listen by Ariel Flesler
- Intercept by Ariel Flesler
If this entry left you bewildered, or if you want a quick, well tested solution, you should definitely try one of them. Each works a little differently, but they're all super plugins.
Update: Event Namespacing with Add and Remove
In response to the comment by Nick Johns below, I'm providing an example that allows for both adding a row and removing a row. The code is based on the "Event Namespacing" example above:
-
function addRemoveItemNS() {
-
var $newLi = $('<li class="special">special and new <button class="addone">I am new</button> <button class="removeme">remove me</button></li>');
-
-
$('#list9 li.special')
-
addRemoveItemNS();
-
})
-
});
-
}
-
-
addRemoveItemNS();
-
});
I added an "addone" class to the initial button, but otherwise the list is the same as the others. You can try it out here:
- plain
- special
- plain
22 comments
2 Pings
-
Learning jQuery » Working with Events, part 2...
Learning jQuery » Working with Events, part 2...
-
[...] were. Turns out that jQuery has a mechanism where you can namespace your events. Here is another writeup about it. Nice [...]












hi,
you really put something into this article. thanks.
to avoid the double-binding of events, why dont we just "tag" the elements that already got the event attached
maybe faster than unbinding/rebinding *all* events.
of course we still have to call addEvent() when needed:-/...
-till
Hi Till,
Yes, tagging elements that have the event already bound is a great way to avoid the multiple binding problem. Thanks for the suggestion!
First off, I'm starting to seriously look at jQuery as a tool for everyday scripting needs, and this site is a great way of showcasing the value of this library. Thank you!
Second off, I'm writing because I primarily use Safari (3.1.1) for the Mac (OS X 10.5.3) and the .clone(true) example didn't work. The cloning part worked, but the event binding did not. I tested this in Firefox also, and everything worked fine, so I know it's not a problem with your code but, rather, with Safari.
$(document).ready(function() {
$('#list4 li.special button').click(function() {
var $parent = $(this).parent();
$parent.clone().append(' I\'m a clone!').insertAfter($parent);
});
});
My AJAX call is updating DOM of the upload form by creating one additional input box which I need to submit along with values of other controls existing in the DOM prior to AJAX call.
However, this is not the case. Although I can see the value of the new element, it does not get posted. The workaround I am using is to copy the value of this element on submit to another, hidden, existing prior to AJAX call, and retrieve that value after submitting. Is there a way that I make the form aware that it should post the value of the new element created by AJAX?
Great article, thanks!
What is my problem
I´m using this code inside an javascript function
and i need to press the button where i caal this function twice to make my php the code run
function GetData(_url, n){
$(document).ready(function(){
$("#save").click(function(){
$("#res p").load("salvar_lista.php"+_url+"&lista=lista"+n);
});
});
}
Hello Karl.
I have one question about this bind & unbind.
If we take a line of your code as an example.
Here after insertion I don't want to perform the old functionality. Lets say on this button's click Event i want an alert. How is that possible.....
Please Explain.....soon
-----------------------------
I changed the id of button and onClick call an alert("ABC"); but invan. (Even remove all unnecessary ids etc..)
Hi Tahir,
You simply bind the click event to the new
<li>after insertion. An easy way to do this is to start with$newLiand use.insertAfter()rather than.after(). Here is a simplified example:That should allow the newly created button to produce an alert when clicked.
Thanks Karl.
You really gave me great reply.
Ok. I have a question in jquery documentation it is said that .bind will bind every matched element on the document. but with .bind this statement does not feel true. I copy and paste list <ul> and it work on first one fine but on second list it does not respond. Even i copy the code from Jquery.com and learningjquery.com and apply the same practice. is there any problem or modification of code required is it possible without changing the #id of 2nd <ul> and then bind is again.
Hi Tahir,
I'm not sure I follow your question. Are you using the same ID for more than one <ul>? If so, that will cause problems. If you could post a test page that exhibits the problem you're having, I'll have a better chance of detecting the problem
I hope the question is relative: Suppose I have a page that is loaded once and anything on it gets done through AJAX. I have a "main" div which is updated through an ajax call when a click is made.
For example, at the beginning main contains some anchors with class="alert" which bind an alert to click(). At some point in time, main is replaced by some new HTML (from an AJAX call) so there are no more anchors with class="alert".
The question is: Are the initially bound handlers also cleared along with the removed elements? Do I have to unbind everything before an AJAX call replaces html with bound handlers to avoid memory leaks?
Sorry for my delay I was busy in other things.
Sorry for my delay I was busy in other things.
Ok Here is my question.
if there is a list like in the document.
$('#list8 li.special button').bind('click', addItemFinal);
and after that there is another list with the same name and both loaded at the same time. It apply the effect on first one. but does not work on the second one Why. I resolved it like this
$('#list8 li.special button').bind('click', addItemFinal);
$('#list9 li.special button').bind('click', addItemFinal);
while it should work like this.
$('#list8 li.special button').bind('click', addItemFinal);
As it is said that Effect is applied to all the DOM elements as with the same reference.
I tested other sort of things with the same concept like changing colors etc those thing works fine (not in this example).
Hello there,
Regarding Bind/unbind this article bring me more confusion than what it solves.
Why do you use Append methods (addItemFinal, .append, etc,etc) when you can explain it more generally with, after you load your external data, just type the bind method again, period!
Example :
Explained:
The last line simply binds the click button of #refreshLinks to the function actualizarLinks for the function to called.
Inside the function, we call request the page with ajax, and update our #links with the data returned, then, we just rebind (bind again), the click method of #refreshLinks to the actualizarLinks function.
Hope this clears any future confusion, like the one i had.
Great posts Karl! I'm still new to jQuery, but it is coming along quick. One thing I'm still not equipped to do is make the decision between event delegation and re-binding. Event Delegation seems to have great performance characteristics but ties you to a couple specific named elements. Re-binding would allow you to make completely dynamic nests of divs. Is there one you prefer?
I have a situation where I'll be adding several divs that I want to have a certain behavior. Rather than go through re-binding them, I was thinking of creating a hidden div that has all the behavior bound to it, and then when I need to "add" the div, I'll just use clone(true) on the hidden div and change the id and remove my "hidden" class. This way I don't have to spend much time worrying about rebinding. Does this approach have merit, or is there a drawback that I'm not considering?
For Re-binding Basics, I tried the example on this page, but got a problem about producing a multiplier effect. To be better presenting my problem, I cut this example to a new page:
http://www.61dh.com/qna/binding.html
I would appreciate it if someone can help me out. (adamcai@live.com)
Happy Thanksgiving!
Hi Adam,
You need to keep reading this entry all the way through the end, or at least through the section called "Unbind, then Rebind" . It looks like the code you copied comes from the example halfway through the entry.
Hi Karl!
Thank you for the quick response. I did understand "Unbind, then Rebind" would fix the problem of producing a multiplier effect, but my question was that I do know understand the behavior of producing a multiplier effect, (e.g. why in some circumstance, when you click the last button of 'I am new', it produces 3 new buttons instead of one?)
Please see the example at http://www.61dh.com/qna/binding.html, you may know what I was talking about. Sorry for the confusion!
Thanks again!
Well, this seems to be nice and dandy but what if the incoming AJAX based html is not known but contains accordions, thinkboxes, etc, etc.
Is there a generic way of doing this ?
For example I have few areas on the page that bring html via various mechanisms from a remote location - mainly AJAX. I have no idea how the data would look but it may have accordions, tabs, modal boxes(thickbox) - how do I rebind those ?
Calling the document.ready wouldn't do it because the areas that don't refresh are going to bind again creating a nightmare. Ideally would be nice to rebind only the newly refreshed element(divs)
Is there a way to achieve this ?
How would you add a second button to REMOVE the line? There are loads of examples of inserting lines but what about removing? thank you for your help.
Hi Nick,
Excellent question! I've updated the post to show an example of adding and removing items.