Working with Events, part 1

read 80 comments

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:

JavaScript:
  1. $(document).ready(function() {
  2.   $('button.alert').click(function() {
  3.     alert('this is an alert message');
  4.   });
  5. });

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:

JavaScript:
  1. $('#create-button').click(function() {
  2.   if ( $('button.alert').length <2) {
  3.     $('<button class="alert">Not another alert').insertAfter(this);
  4.   }
  5.   return false;
  6. });

create the button

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:

HTML:
  1. <ul id="list1" class="eventlist">
  2.   <li>plain</li>
  3.   <li class="special">special <button>I am special</button></li>
  4.   <li>plain</li>
  5. </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:

JavaScript:
  1. $(document).ready(function() {
  2.   $('#list1 li.special button').click(function() {
  3.     var $newLi = $('<li class="special">special and new <button>I am new</button></li>');
  4.     $(this).parent().after($newLi);
  5.   });
  6. });

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:

JavaScript:
  1. $(document).ready(function() {
  2.   $('#list2').click(function(event) {
  3.     var $newLi = $('<li class="special">special and new <button>I am new</button></li>');
  4.   });
  5. });

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:

JavaScript:
  1. $(document).ready(function() {  
  2.   $('#list2').click(function(event) {
  3.     var $newLi = $('<li class="special">special and new <button>I am new</button></li>');
  4.     var $tgt = $(event.target);
  5.     if ($tgt.is('button')) {
  6.       $tgt.parent().after($newLi);
  7.     }
  8.  
  9.     // next 2 lines show that you've clicked on the ul
  10.     var bgc = $(this).css('backgroundColor');
  11.     $(this).css({backgroundColor: bgc == '#ffcccc' || bgc == 'rgb(255, 204, 204)' ? '#ccccff' : '#ffcccc'});
  12.   });
  13. });

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:

JavaScript:
  1. $(document).ready(function() {
  2.   $('table').click(function(event) {
  3.     var $thisCell, $tgt = $(event.target);
  4.     if ($tgt.is('td')) {
  5.       $thisCell = $tgt;
  6.     } else if ($tgt.parents('td').length) {
  7.       $thisCell = $tgt.parents('td:first');
  8.     }
  9.     // now do something with $thisCell
  10.   });
  11. });

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.

comment feed

80 comments

  1. Great article, always so clear and focused, congratz!

    P.S: I never thought about the CSS/JS comparison. Good point there.

  2. mrrookie

    Great stuff, i was wondering precisely that :p.

    Thanks for sharing!

  3. Nice tutorial on event delegation, Karl.

  4. Ivan

    Delegation is definitely the future of javascript frameworks. It not only performs better, but is much better suited to highly dynamic applications.

  5. Kai

    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.

  6. 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.

  7. 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.

  8. Steve

    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

  9. Hi Steve,

    I'm flattered by your comments, and happy to see that your question to the jQuery UI group has been answered there.

  10. Love this method, would never have thought of doing it that way.

  11. roland

    That was very enlightening. One could also have a look at the liveQuery plugin, by the way.

  12. 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.

  13. 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.

  14. 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:

    1. Attribution. You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work).
    2. Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting work only under the same or similar license to this one.
  15. Thanks ;)
    Best wishes.

  16. Thanks just a lot.
    By the way very nice the new
    layout.
    Zen it's the first think
    I thought of ;)
    Best wishes.

  17. In all my applications I use livequery plugin - it's great one!!!

  18. 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.

  19. 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!

  20. 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.

  21. 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

  22. exlente articulo, muchas gracias !!

  23. Muy bien explicado para todos los novatos en Jquery. Thanks

  24. Nice blog Karl! I've updated my blogpost with a link to this blog!

  25. Thanks so much, Jonas! Glad you like the blog. Jag älskar jQuery, too. ;)

  26. Lang

    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.

  27. 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:

    <div id="container">
      <form class="create" method="post" action="foo.html">
        <!-- all your form elements in here -->
        <button>create</button>
      </form>
    </div>

    Your jQuery would be something like this:

    $('#container').click(function(event) {
      // fun happens here ...
    });
  28. Lang

    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

  29. Lang

    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.

  30. I never would have though about doing it this way! ... Thanks for the tut! :D

  31. Hi all where can i find more information about this?

  32. santhosh

    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.

  33. 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:

    $(document).ready(function() {
      $('button.alert').click(function() {
        alert('this is an alert message');
      });
    });

    More information on document ready.

  34. Rafael Rosa

    Karl,

    You just saved my life :) I'll subscribe your RSS right now.

    Thanks a lot,
    Rafael Rosa
    GPI TI
    São Paulo - Brazil

  35. kenandalda

    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

  36. Tahir

    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.

  37. 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.

  38. Tahir

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

  39. Tahir

    I put it there jQuery Google Group as well with the heading

    Problem in Handling Events after insertBefore()

  40. Thanks to your postings, there is a weight off my mind. Downloaded the official jQuery book and it's gobbledegook to me. This makes practical sense.

  41. Hi Fred,
    I really appreciate the feedback and am glad that you like the blog. Just out of curiosity, which book did you download. Three have been written, but there is no "official" book.

  42. Quintin

    Hello,

    I must be the only one here that does not get this article - maybe it´s because I´m a absolute beginner to all this. The problem I have is trying to get jQuery to do the .wrapAll function more than once. Would this article be related to my problem?

    Thanks!

  43. Dan Scrima

    Hey great article; I'm trying to figure out if this is my issue or not actually.
    I have a table with the column of each row a checkbox. When the user clicks the checkbox, a popup appears using JQuery's $.ajax and shows a JSP page that has a simple div with a an input textbox and a button to submit. I'm trying to validate that the textbox has a value before submitting. The problem is, when I click a second checkbox, the value for the textbox in my generated popup is still what it was previously, so the validation obviously doesn't work. I'm using tag libraries, so please ignore the actual tagnames themselves, as this is a mockup. :)

    Here is the JQuery code to attach my jsp to the popup:

    
    showPopup: function() {
       var data = {};
       $.get('myPopupPage.jsp', {},
                   function(data) {
                          var html = JQuery(data).html();
                          $(control).showTip(html, {height:50,width:50});
                   }, 'XML';
    }
    

    Here is the jsp page that is attached to my popup:

    
    <div class="reasonDiv">
       <input id="reasonFreeText"/>
       <input type="submit" onclick="$(this).addText($('#reasonFreeText').val())"/>
    </div>
    

    Here is the JQuery function that is triggered from the popup:

    
    addReason: function(textFromTextbox) {
         alert(textFromTextbox);
    }
    

    The second time I run this, the alert still gives me the original value! :(

    Thanks for any help!

  44. Hi Dan,
    Some browsers, Firefox in particular, have a hard time letting go of values previously entered in a text field. Still, I'm not sure why it's happening here, since you're injecting a whole new form, or so it seems. Anyway, you should be able to set the value to an empty string — $('#reasonFreeText').val(''); — first thing inside the $.get() callback.

  45. Dan Scrima

    Thanks Karl I'll definitely try it!
    JQuery seems to have so much potential if it didn't get so confusing :)
    Then again, the AJAX methodology natively isn't the nicest thing to begin with.

  46. Thank you very much for this article, now i really understand how to handle events on inserted html and generated html. Thanks again

  47. Abhishek

    Hi great work Karl,this article is simple and easy to implement,good for jQuery beginners like me
    Thanks

  48. santosh

    Hi, Nice article. But I want to convert following javascript code to jquery code. I tried it in many ways but no result... please can you help me to convert it in jquery

    
    var e = window.event;
    	var tg = (window.event) ? e.srcElement : e.target;
    	if (tg.nodeName != 'DIV') return;
    	var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement;
    		while (reltg != tg && reltg.nodeName != 'BODY')
    		reltg= reltg.parentNode
    	if (reltg== tg) return;
    
  49. mk

    Thanks so much for your article. I've been puzzled with event delegations and now I understand thanks to your article.

  50. davos

    I can't thank you enough Karl - I've been jquery-ing for about a year, and have missed event.target completely! I've often wondered about the cost of binding click events to lots of elements (last time was about 3 hours ago!) - when explained so clearly and succinctly, it's so obvious :) keep posting!

  51. I am using event delegation in asp.net master pages.
    When i attach the event using event delegation on the master page then everything works fine but when i write the same script on the content page the event is executed twice, say i print a alert("Hello") on the click of a button which is generated using jTemplate in jquery on the content page then this hello displays two times when placed on content page.
    So how to solve this problem i cannot keep all the script code on the master page
    Please Help

  52. Thanks
    But i figured out it was my mistake i havenot deleted my cache it was bringing things from cache and thus the event was firing twice.
    After clearing the cache the things are now working fine.
    Thanks for such a great article.

  53. Gaurav

    Awesome post. Thanks a lot for the tutorials. Great site.

  54. This post gave us a major Brainstorm session of all the possibilities we can utilize on our blog.

  55. Jas

    Great Article, and very much in need. I am attempting execute as a hover, but can't seem to get it working and have traced back to event.target not giving me what i would expect.

    If I run code below, on hover, the event.target returned is [object Object]??

    Any ideas what I am doing wrong?

    Thanks again for great post and topic.


    $("#subsTable").hover(
    function (event) {
    var $tgt = $(event.target);
    alert('target is: ' + $tgt);
    },
    function (event) {
    $(this).removeClass("second");
    }
    );

    • That is, actually, what I would expect alert to report.

      Try using .mouseover() and .mouseout() instead. And if you still want to alert something, try the id instead: alert('target is: ' + event.target.id);

  56. Jas

    Guys, you need to set some client side validation on this form. I just submitted a big long post, but lost it all because I forgot to enter my name and email. Jeepers!

    In short, Karl.. you're a champ. You set me on the right path with that. Here is the code that works for doing a mouseover addClass/removeClass on a tablesorter table:


    $('#subsTable').mouseover(function(event) {
    var $tgt = $(event.target);
    if ($tgt.is('td')) {
    $tgt.parent().addClass("second");
    }
    }).mouseout(function(event) {
    var $tgt = $(event.target);
    if ($tgt.is('td')) {
    $tgt.parent().removeClass("second");
    }
    });

    Original problem was that I thought my event.target would be a tr, but it was not, it was the td.

    One question from your post. You mention I can get the id of the event.target to display in an alert() with "event.target.id". How would I get the node name. For example, to alert whether the event.target is a td, tr, span, div, li etc... ?

    Thanks Karl for your assistance, and a great article. You've saved a world of people a world of headaches.

    • So sorry that you lost your post! I'll definitely add client-side validation asap. Can't believe I haven't done that yet.

      Glad you like the article, and thanks for your kind words.

      To get the node name, you can use … event.target.nodeName. :) event.target.tagName works, too.

  57. Jake

    As of Jquery version 1.3 you can now use the live() function to bind current - and future - matched element.

    E.g.


    $(document).ready(function() {
    $('#list1 li.special button').live('click', function() {
    var $newLi = $('<li>special and new I am new</li>');
    $(this).parent().after($newLi);
    });
    });

  58. lion

    I've been struggle for so long to understand why we use event delegation (yes i'm noob). Your article is savior.

  59. Zbynja

    perfect article Karl, very concise and useful, brilliantly explained .. thank you much for it.

  60. Thanks for the code snippets... found it very useful.

  61. Shree Krishna

    Ver naice tutorial for those who want to begin jquery.

    Thank alot

  62. John

    Why have you put the code text in light grey against a white background...it is practically unreadable on my monitor. Bad design.

  63. Ivan S.

    I sent an email to Karl asking for some help. Perhaps someone here could help before he replies to me. I'm not sure if I need to use event delegation. I have two tables. Table 1 has a "Add" button that will remove that row and add it to Table 2. That all works. Table 2 also has a "remove" button that will remove that row and add it back to Table 1.

    Initially, I used live('click',function()) and it seemed to work. When the table result set started to grow exponentially, the loading of the page got really slow. In fact, after any mouse event on the page, the page just hangs. I tried using livequery but that didn't do anything. I am looking to achieve this through event delegation but not even sure how to bind the "remove" button event to the new row in Table 2. Any help appreciated.

    Thx

    Ivan S.

  64. Fu

    Your article is very helpful for me. Thanks for sharing

  65. I've finally figure out the reason why onclick doesn't work with dynamically added elements. Really usefull article, thanks a lot!

  66. Very nice and useful tutorials to web designers,
    Thanks for posting.

  67. bob

    A little advice, instead of doing this:

    if ($tgt.is('td')) {
    $thisCell = $tgt;
    } else if ($tgt.parents('td').length) {
    $thisCell = $tgt.parents('td:first');
    }

    You can simply do this (jQuery 1.3 and above)

    $thisCell = $tgt.closest('td');

    Closest first looks at the initial element to see if it matches the selector, and if it doesn't goes up through the DOM tree and finds the first element that matches the selector.

    Might be a good idea to replace the code in the main article.

    • Hi Bob,
      Yeah, I really should update the article. Note that it was written before jQuery 1.3, and at the time .closest() didn't exist. We're well aware of the method and have written about it in more recent tutorials.

      thanks.

      • Nit: if you had a table within that cell, you might actually be targeting a nested cell.

        You would want to find the "highest" td element between the event target and the wrapping delegation element (i.e. the td that's closest to "this").

        Would this be the best way?

        
        $(function() {
            $('table.outer').click(function(event) {
                var parentCells = $(event.target).parentsUntil(this).filter('td');
                var outermostCell = $.merge($(event.target), parentCells).last();
                // now do something with outermostCell
          });
        });
        
  68. Patrick P.

    Hello,

    thank you for this article, which is pretty much the first stuff I read about jquery.

    I found jquery while looking for a solution to my jquerylightbox problem: I refresh my "content" div with new content and the lightbox won´t work anymore. So event delegation seems to be the solution, but I am not sure how to set it up.

    I need to keep all links within my content div and the tag rel="shadowbox" binded to the the lightbox:

    $(function() {
    $('a[@rel*=lightbox]').lightBox();

    });

    A little help please! :)

    thank you!

  69. Sandino

    Nice article I help me a lot really.
    Thanks for sharing so good information all your posts are great.

    I personally starting to work with jquery using live function:

    $('#boton_creador').click(function(){
    $('#algo').before('');
    });

    $('#aun_no_creado').live('click', function(){
    $(this).parent('div').animate({opacity: 'hide', height: 'hide', marginBottom: '0px'}, 'fast',
    function () {
    $(this).remove();
    });
    return false;
    });

  70. Thank you very easy to follow, and has helped me to understand more about events

  71. thanks for providing the download/script list used in the exercise (wish everyone did that!) :)

  72. Nikhil

    great information about event delegation in JQuery. Thanks a lot!

29 Pings

  1. Learning jQuery » Working with Events, part 1...

    Learning jQuery » Working with Events, part 1...

  2. [...] Learning jQuery talks about event delegation with examples in Working with Events. [...]

  3. [...] my last article, I described the common problem of events seemingly ceasing to work for new elements added to a [...]

  4. [...] Working with Events by Karl Swedberg - http://www.learningjquery.com/2008/03/working-with-events-part-1 Leave a Reply Visited 1 times | Tags: Javascript, jQuery, Optimization, Web Development Customizing FCK Editor toolbars in PHPConstituents of a PHP based Open source Web Development EnvironmentCreating a simple bar chart using pChart Library in PHP [...]

  5. [...] Working with Events: Part 1 [...]

  6. [...] you want to read further: check out this great article by Karl Swedberg. [...]

  7. [...] delegation, as described in the first article of this series, is a way to take advantage of event bubbling to avoid binding an event listener more than once. [...]

  8. [...] Read this article: Working with Events, part 1 » Learning jQuery – Tips, Techniques, Tutorials [...]

  9. [...] delegation, as described in the first article of this series, is a way to take advantage of event bubbling to avoid binding an event listener more than once. [...]

  10. [...] delegation, as described in the first article of this series, is a way to take advantage of event bubbling to avoid binding an event listener more than once. [...]

  11. [...] 原文地址:http://www.learningjquery.com/2008/03/working-with-events-part-1 原文作者:  Karl Swedberg [...]

  12. [...] was reading a blog post about jQuery event delegation by Karl Swedberg yesterday. One corner case I found in his examples is dealing with nested DOM [...]

  13. [...] Working with Events, part 1 » Learning jQuery – Tips, Techniques, Tutorials (tags: jquery) [...]

  14. [...] For example, let’s say we have “<button>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: PLAIN TEXT [...]

  15. [...] Working with Events, part 1 [...]

Sorry, but comments for this entry are now closed.