Working with Events, part 1
CSS and JavaScript are different in many ways, almost all of which are too obvious to mention. However, one difference between the two bears explanation, because it is often the cause of confusion and consternation, especially among those who are making the transition from CSS guru to jQuery novice. In fact, it was one of the first things I asked about on the jQuery mailing list back in 2006. Since then, I've seen at least one question on the subject every week, and sometimes as many as one per day—despite an FAQ page and these three plugins to help users deal with it.
How CSS and JavaScript Are Different
So, what's this important difference?
In CSS, style rules are automatically applied to any element that matches the selectors, no matter when those elements are added to the document (DOM).
In JavaScript, event handlers that are registered for elements in the document apply only to those elements that are part of the DOM at the time the event is attached. If we add similar elements to the DOM at a later time, whether through simple DOM manipulation or ajax, CSS will give those elements the same appearance, but JavaScript will not automatically make them act the same way.
For example, let's say we have "<button class="alert">Alert!</button>" in our document, and we want to attach a click handler to it that generates an alert message. In jQuery, we might do so with the following code:
Here we are registering the click handler for the button with a class of "alert" as soon as the DOM has loaded. So, the button is there, and we have a click function bound to it. If we add a second <button class="alert"> later on, however, it will know nothing about that click handler. The click event had been dealt with before this second button existed. So, the second button will not generate an alert.
Let's test what we've just discussed. I've added a script with the above three lines of jQuery code so that the following button will produce an alert message when clicked. Try it:
Events Don't Work with Added Elements
Now, let's create a new button (if we don't already have a second one) using jQuery code like this:
-
}
-
return false;
-
});
Have you clicked the link to create the second button? Great. Now click that button. It does nothing. Just as expected.
CSS Continues to "Work" with Newly Created Elements
Now let's take a look at another example. In this one, we have three list items—two plain items and one with a class of special:
-
<ul id="list1" class="eventlist">
-
<li>plain</li>
-
<li class="special">special <button>I am special</button></li>
-
<li>plain</li>
-
</ul>
Press the "I am special" button to create a new list item with a class of "special":
- plain
- special
- plain
Notice that, like the first special li, the new one has the yellow background. The CSS has come through for us. But press the newly created "I am new" button and, just as with the second alert above, nothing happens. The jQuery code we're using to add the new item says that upon clicking a button inside a list item with a class of "special" (which itself is inside an element with id of "list1") a new list item with class="special" should be inserted after the list item in which the button was clicked:
So, how can we get the events to carry over to the new elements? Two common approaches are event delegation and "re-binding" event handlers. In this entry, we'll examine event delegation; in part 2, we'll explore ways to re-bind.
Event Delegation: Getting Events to Embrace New Elements
The general idea of event delegation is to bind the event handler to a containing element and then have an action take place based on which specific element within that containing element is targeted. Let's say we have another unordered list: <ul id="list2"> ... </ul>. Instead of attaching the .click() method to a button — $('#list2 li.special button').click(...) — we can attach it to the entire surrounding <ul>. Through the magic of "bubbling," any click on the button is also a click on the button's surrounding list item, the list as a whole, the containing div, and all the way up to the window object. Since the <ul> that gets clicked is the same one each time (we're only creating items within the <ul>), the same thing will happen when clicking on all of the buttons, regardless of when they were created.
When we use event delegation, we need to pass in the "event" argument. So, in our case, instead of .click(), we'll have .click(event). We don't have to name this argument event. We can call it e or evt or gummy or whatever we want. I just like to use labels that are as obvious as possible because I have a hard time keeping track of things. Here is what we have so far:
So far, the code is very similar to our first attempt, except for the selector we're starting with (#list2) and the addition of the event argument. Now we need to determine whether what is being clicked inside the <ul> is a "special" button or not. If it is, we can add a new <li class="special">. We check the clicked element by using the "target" property of the event argument:
-
var $newLi = $('<li class="special">special and new <button>I am new</button></li>');
-
var $tgt = $(event.target);
-
if ($tgt.is('button')) {
-
}
-
-
// next 2 lines show that you've clicked on the ul
-
$(this).css({backgroundColor: bgc == '#ffcccc' || bgc == 'rgb(255, 204, 204)' ? '#ccccff' : '#ffcccc'});
-
});
-
});
Line 4 above puts the target element in a jQuery wrapper and stores it in the $tgt variable. Line 5 checks whether the click's target is a button. If it is, the new list item is inserted after the parent of the clicked button. Let's try it:
- plain
- special
- plain
I put an additional two lines at the end to demonstrate that a click on one of the buttons is still considered a click on the <ul> You'll see that clicking anywhere within the <ul> toggles its background between pink and blue.
It's probably worth noting that jQuery makes working with the event argument cross-browser friendly. If you do this sort of thing with plain JavaScript and DOM nodes, you'd have to do something like this:
var list2 = document.getElementById('list2');
list2.onclick = function(e) {
var e = e || window.event;
var tgt = e.target || e.srcElement;
if (tgt.nodeName.toLowerCase() == 'button') {
// do something
}
};
As you can see, it's a bit of a hassle.
Another Huge Benefit of Event Delegation
Event delegation is also a great way to avoid crippling the user's browser when you're working with a huge document. For example, if you have a table with thousands of cells, and you want something to happen when the user clicks on one, you won't want to attach a click handler to every single one of them (believe me, it can get ugly). Instead, you can attach the click handler to a single table element and use event.target to pinpoint the cell that is being clicked:
Note that I had to account for the possibility of clicking in a child/descendant of a table cell, but this seems a small inconvenience for the great performance increase that event delegation affords.
Coming Up Next
In part 2 of this tutorial, we'll look at how to get events to carry over to newly created elements through careful placement of function calls. We'll also, necessarily, examine unbinding events and using namespaced events. In the meantime, I hope you find part 1 useful. If I've made any mistakes, especially in my terminology, please don't hesitate to point them.



March 31st, 2008 at 12:48 pm
Great article, always so clear and focused, congratz!
P.S: I never thought about the CSS/JS comparison. Good point there.
March 31st, 2008 at 3:15 pm
Great stuff, i was wondering precisely that :p.
Thanks for sharing!
March 31st, 2008 at 3:38 pm
Nice tutorial on event delegation, Karl.
March 31st, 2008 at 6:43 pm
Delegation is definitely the future of javascript frameworks. It not only performs better, but is much better suited to highly dynamic applications.
April 1st, 2008 at 6:15 am
Learning jQuery » Working with Events, part 1...
Learning jQuery » Working with Events, part 1...
April 2nd, 2008 at 10:31 am
Sorry, I forgot to wrap the code properly.
var $newLi = $('<li class="special">special and new <button>I am new</button></li>');
var newLi = '<li class="special">special and new <button>I am new</button></li>';
What's the difference between using these two lines? Thanks.
April 3rd, 2008 at 8:03 am
one word: Fabulous.
What a enlightening article!!
Kai, the first one find and returns the DOM element thru jQuery. The second, contain only the string with the
<li>structure.April 3rd, 2008 at 9:00 am
thanks for the compliments.
Kai, I think I wrapped the
<li>in$()out of habit. It's often useful to do that for chaining, but in this case it's unnecessary since just putting a string into the.append()will work fine.April 3rd, 2008 at 11:28 am
Excellent article! This really helped my understanding of this particular phenomenon. I have a specific implementation problem, which I've described here:
http://groups.google.com/group/jquery-ui/browse_thread/thread/6d5c47a6f7be900e
I'd be interested to hear your thoughts
And by the way, I just bought your book, so I look forward to expanding my jQuery mind well beyond its current, embryonic state.
Cheers
Steve
April 3rd, 2008 at 12:09 pm
Hi Steve,
I'm flattered by your comments, and happy to see that your question to the jQuery UI group has been answered there.
April 4th, 2008 at 7:25 pm
Love this method, would never have thought of doing it that way.
April 5th, 2008 at 8:47 am
That was very enlightening. One could also have a look at the liveQuery plugin, by the way.
April 5th, 2008 at 4:50 pm
Hi Roland,
You're absolutely right. In fact, I linked to the liveQuery plugin in the entry above where I refer to "these three plugins." In retrospect, I probably should have called them out more obviously. Thanks for the comment.
April 5th, 2008 at 7:08 pm
Hi.
).
Sorry to disturb you.
I'm a beginner at jQuery.
I'm very fond of it, it's very funny
and so powerfull (violin
I like very much your blog so I'd
like to translate from english to italian
a few of your articles.
I'm wondering would you agree ?
Bye.
April 6th, 2008 at 9:02 pm
Hi whisher,
Not disturbing me at all. You are free to translate as many articles as you wish, under the terms of the Creative Commons license. In fact, I'd consider it an honor.
The license is straightforward; here are the two main terms:
April 7th, 2008 at 10:09 am
Thanks
Best wishes.
April 7th, 2008 at 10:13 am
Thanks just a lot.
By the way very nice the new
layout.
Zen it's the first think
I thought of
Best wishes.
April 11th, 2008 at 2:54 am
In all my applications I use livequery plugin - it's great one!!!
April 14th, 2008 at 9:38 pm
This is pretty much what I need to solve my current issue of itmes not doing what they're supposed to do, after having been created on the page through Javascript.
I'll give this a go, and if I can't get it to go, I'll try the Live Query Plugin. Thanks for the clear explanation.
April 16th, 2008 at 10:54 am
Good articles!
I always meet these kind of problems! especially when using ajax. some new elements created, I should bind event handlers for it. I think this article can help me for that.
Thanks!
April 21st, 2008 at 2:02 am
Hi,Thanks for ur information.Great article, always so clear and focused and enlightening. One could also have a look at the live Query plugin, by the way.Yes,Delegation is definitely the future of javascript frameworks. It not only performs better, but is much better suited to highly dynamic applications.
April 23rd, 2008 at 12:48 am
Thanks for the article. I am trying my best to learn how to use jquery and want to try to integrate it with my current site.
Does the following sound plausible?
in the onclick method of a text element I call a javascript function. Through this function I update database values for that field. This works now.
Would I be able to also add a jquery call to that function which would add a class to all of the input elements in that page to indicate the page had been updated by changing the color of the text in the input elements.
I realize this can be done separately but didn't know if it was possible to combine the two methods.
Thanks,
Michael
April 24th, 2008 at 3:48 pm
exlente articulo, muchas gracias !!
May 3rd, 2008 at 11:33 am
Muy bien explicado para todos los novatos en Jquery. Thanks
May 4th, 2008 at 2:40 pm
Nice blog Karl! I've updated my blogpost with a link to this blog!
May 4th, 2008 at 3:24 pm
Thanks so much, Jonas! Glad you like the blog. Jag älskar jQuery, too.
May 7th, 2008 at 2:21 am
I have a situation that is slightly different than that given in this article, apparently different enough that I have not been successful in applying the delegation pattern. I am hoping you can help. Here is a pastie of the problem with relevant comments. I sure would appreciate your help.
May 7th, 2008 at 2:00 pm
Hi Lang,
It looks like you are creating a whole new form when you click the button, but the selector -- either $('.delete') or $('.create') -- refers to the class name of the form. For event delegation to work, you can't bind the event handler to the element that has not yet been created. My suggestion is to bind it to a containing element.
For example, wrap a div around the form(s) and bind the "click" handler to that. So, if your markup looks something like this:
Your jQuery would be something like this:
May 7th, 2008 at 4:27 pm
Thanks Karl. I wrapped the form in a div and insertAfter the new form upon ajax success. The problem I am having now is that the replaced form click event is firing as soon as the new form is inserted resulting in another ajax call. At least event delegation is happening now, but obviously I am missing something. I would appreciate help figuring out why the event is firing on the newly inserted form. Here is a link to the modified version: http://pastie.caboo.se/193224
May 8th, 2008 at 12:38 am
I figured it out. Been coding jquery and javascript for a total of two days now, so newb error. Anyway, the livequery plugin is the ticket for rebinding events. I am posting the conclusion here in case it helps someone else. Note that the part you don't see in the code is an enclosing td element with an id of td_: http://pastie.caboo.se/193457 . Thanks for the great information on jquery.
May 28th, 2008 at 4:07 pm
I never would have though about doing it this way! ... Thanks for the tut!
June 2nd, 2008 at 12:01 pm
Hi all where can i find more information about this?
June 21st, 2008 at 6:08 am
Hi,
I am beginner to jQuery. i am trying to execute the following script through jquery, but i am not getting what am i expecting. can you please tell me where am i making mistake.
window.onload = function(){ alert("abc") }
$('button.alert').click(function() {
alert('this is an alert message');
});
Click me
this suppose to give me alert message when i click the button but it is not. i have put the jquery.js in the same folder where i have the html file.
Thank you.
June 25th, 2008 at 3:31 pm
Hi Santhosh,
you'll need to put the other part of the code in either the same window.onload handler or in document ready. Document ready is typically preferred:
More information on document ready.
July 1st, 2008 at 2:16 pm
Karl,
You just saved my life
I'll subscribe your RSS right now.
Thanks a lot,
Rafael Rosa
GPI TI
São Paulo - Brazil
July 30th, 2008 at 1:22 pm
You just saved my life too, thank you very much!:)
I'd add your blog to my Favorates and subscribe its rss.
Kenneth Chen
Beijing-China
August 19th, 2008 at 6:29 am
hey nice work.
Could you please elaborate more alert functionality.
Actually this is great exp. but i still got problem. when i click a button it insert();
and then at that i apply some functionality like alert(); and it does not work.
so please elaborate ur first example....... plz soon.
August 19th, 2008 at 8:57 am
Hi Tahir,
Perhaps you could direct your question to the jQuery Google Group. I think you'll have a much better chance of getting a satisfactory answer and will be able to follow up with additional questions more easily. Please describe as clearly as you can the outcome you're trying to achieve and show the code that you have written so far.
August 19th, 2008 at 9:40 am
Hey Karl thanks for ur suggession. I had posted it there plz take a look i hope u can solve it soon. as you was showing the same example in the above tutorial.
i have this problem when i call a function onClick after insertBefore();
when i click a button it insert TEXT AREA, SEND BUTTON at right place.
and then at that i apply some functionality like ALERT("ABC"); at that inserted BUTTON and it does not work.
Help me out of this ... plz soon.
* Code is OK if i does not put it in this snario. Only when i dynamically insert some tage and apply an event to those it does not work *
------------------------------------------------ OK (it inserts at relevant position) ----------------------------------------
$("div#sec_news_comments_stats").click(function () {
$("|id-|' value='' />Save Comments").insertBefore($(this).parent()).hide();
$("div#sec_news_comments").slideDown("slow");
}
-------------------------------------------------------------- Problem () ----------------------------------------------------------
$("div#add_comments").click(function(){
alert("Hello add_comments"); // Some functionality but it did not even gave alert.
});
August 19th, 2008 at 10:23 am
I put it there jQuery Google Group as well with the heading
Problem in Handling Events after insertBefore()