• jQuery Live Events

    Feb 16 2009

    jQuery 1.3 came out on January 14th, jQuery 1.3.1 on the 21st, and with them we now have live events built into jQuery.

    Live events are pretty magical at first glance. They allow you to set events only once, and they work forever in the future, even as you're creating new elements and adding them to the page.

    Normally if you ran:

    $('a.wizard').click(function(){
        // do some wizardry
    });
    

    and then later you added wanted to add some more <a class="wizard">s to the page, you would have to re-attach this event handler over and over.

    Live events allow you to add an event that will work forever. This means you only have to add each type of event once. You would only have to write:

    $('a.wizard').live('click', function(){
        // do some wizardry
    });
    

    And your wizard links will work forever, even after you add 100 new wizard links to the page dynamically.

    This magic trick works by attaching the click event to the document. Whenever you click anywhere on the page, the document click event gets called. jQuery compares the target element to your wizard links and triggers your click event if the click came from inside the link.

    You can also do this yourself using the new closest() function. It allows you to do something like this:

    // listen for clicks on the document
    $(document).click(function(e){
        // look for a possible parent element matching a.wizard
        $(e.target).closest('a.wizard').each(function(){
            // wizard it up
        });
    });
    

    These live events can really help with performance. If you're attaching events to 100s of similar elements, like photos in an album, you can also save a lot of memory and speed things up by using live events, or using the example above and checking for events on a common parent element, either document or any element.

    If you're used to using closures to use data within click handlers, you will find they won't work anymore which is probably a good thing. Instead, you can use data() to store any amount of data with that element and get it out later:

    // maybe this is some JSON data you got using Ajax or something
    var wizards = [
       { name: 'Merlin', skill: 'magic' },
       { name: 'Mr. Wizard', skill: 'science' }
    ];
    
    $.each(wizards, function(i, wizard){
        // create a new link, change the text, add the data and append to the body
        $('<a class="wizard"/>')
            .text(wizard.name)
            .data('wizard', wizard)
            .appendTo(document.body);
    });
    

    then you only need to attach the click handler once:

    $(document).ready(function(){
    
        $('a.wizard').live('click', function(){
            // fetch the data back out
            var wizard = $(this).data('wizard');
    
            // get the stuff you need out of the object
            var name = wizard.name;
            var skill = wizard.skill;
    
            // do your thing
            alert(
                "Hello my name is "
                + name
                + "and I'm better than you at "
                + skill
                + "!!!"
            );
        });
    
    });
    

    And you can actually do these things in reverse, the order doesn't matter because of the magic and universality of live events.

    Pretty cool, eh? This way of developing has always been possible using JavaScript, but after learning about this with jQuery 1.3, it changed the way I look at programming with data and events.

    What do you think? Any questions, corrections or suggestions? Leave a comment.

  • Comments

    1. Fred Wu at 8:41pm on February 16, 2009

    One should note that 'live' can only be bind to events, which means LiveQuery (http://plugins.jquery.com/project/livequery) is still the more flexible way of doing live updates, because it can be bind to pretty much any jQuery DOM objects.

    2. :) i :) at 1:43am on February 23, 2009

    I think that you have a really good name for your webpage, but you need someone who helps you in the desing!!!!!!!!!!

    I know a really good one...  his email is proter-@hotmail.com

    3. Jason at 6:08pm on February 25, 2009

    Not to derail this post but..
    @ :) i :)  I'm just a visitor, but I believe the site is rather professionally looking as it is...

    4. thijs at 8:26pm on March 2, 2009

    thanks for pointing this out, it's cool that this is part of the core of jquery now, i did not know that.

    I'm just trying to learn to do some stuff with jQuery, i've never done any javascripting before so it's a steep learning curve but I think a good way in.

    5. Mauvis at 12:37am on March 3, 2009

    For awhile there e.stopPropagation was broken when using jQuery.live, which is logical the way event delegation works in jQuery, but  it was supposedly fixed in the latest release. Haven't check out how they did it, but am glad they found a way.

    6. Thorpe Obazee at 12:36am on April 23, 2009

    Live events are very helpful especially in my last project where I had to bind events at runtime.

    7. Dan at 2:53pm on May 15, 2009

    Hi. Jesse, i need help about , which one is better framework (between mootools and jquery) and why.  thanks
    pd. interesting articles. :D

    8. Jesse Skinner at 2:55pm on May 15, 2009

    @Dan - I'd say jQuery is better but I'm extremely biased and have never used mootools. So maybe you should ask around first :)

    9. Amit Pansare at 8:08pm on June 2, 2009

    Thanks for the neat "coverage" of live events ;).

    10. ZK@Web Marketing Blog at 11:40pm on June 20, 2009

    According to Yahoo! recommendations, script links should be placed in the end of the page, but as I can see, this plugin sends only ‘head’ child tags, doesn’t it?

    11. Andreas Kuckartz at 7:53am on July 7, 2009

    So why did I read about LiveQuery recently?!

    Using a feature which is "built in" seems to be better (usually).

    12. Sean at 4:45pm on July 7, 2009

    I want users of my site to be able to record and play sound. What would be a best option? Flash? Thank you in advance.

    13. Nikolay at 4:06am on July 12, 2009

    @Dan - mootools is not so bad, it is bit lame librarary.
    If you are using it in combination with ASP.NET AJAX you can have a lot headaches :)

    14. Julia at 1:24am on September 14, 2009

    @Jesse i need help plzzzz I have nothing to get from page but i want that whenever any hyperlink on page is clicked it gets count .... same as happening in site statistics software like i dont have any access to body and any element what i can do is just paste a script in head and secondly i am not aware while webpage is ajax enabled or not

    15. Jesse Skinner at 9:56am on September 14, 2009

    @Julia - live events should work well for this. You can do:

    $('a').click(function(){
      // track link
    });

    16. Marlon at 5:05am on October 28, 2009

    I want to hide a specific div tag from an Asynchronously Loading Webpart, is it possible to use the .live() for this? If yes, how? Thanks.

    17. Jesse Skinner at 11:03am on October 28, 2009

    @Marlon - I'm not sure, but it sounds like CSS would do the trick. If the div has a class of dont_show_me then you can have CSS like:

    .dont_show_me { display: none }

    18. Lerroy at 10:14pm on January 27, 2010

    I Love Jquery!

    19. bucabay at 6:16pm on March 9, 2010

    You can't say JQuery is better then MooTools if you haven't even tried MooTools! They really are quite equivalent in functionality...

    20. David Chambers at 10:14am on March 18, 2010

    Actually, bucabay, jQuery and MooTools are philosophically different. MooTools "fixes" areas of JavaScript which jQuery does not touch. [http://jqueryvsmootools.com/#jsfun]

    21. bucabay at 1:19pm on March 18, 2010

    @David Chambers,
    Great link, was a good read. The philosophy may be different in each library, but every library has to offer the popular functionality (in other libraries) in order to survive. Discussing philosophical design guidelines and what not really doesn't pertain to the large majority projects. 99% of time you'll be writing functionality that is implemented in both libraries.

    22. David Chambers at 6:59pm on March 18, 2010

    If one is using jQuery or MooTools primarily to aid DOM traversal and manipulation, I agree that the two are virtually interchangeable.

    If, on the other hand, one is developing a fully-fledged application in JavaScript, one is likely to appreciate the fact that MooTools extends native objects (such as the Date object, which is in need of fixing).

    jQuery and MooTools are both most commonly used in a browser setting. Outside of this setting, however, jQuery has little to offer while MooTools remains relevant. While JavaScript is primarily used as _the_ browser scripting language, it can also be used in contexts such as server-side scripting and Photoshop scripting.

    Please note that while I prefer the broader scope of MooTools I am not suggesting that jQuery is in any way lacking. jQuery is very focused and does what it does extremely well.

    23. bucabay at 11:20pm on March 18, 2010

    I think MooTools is an odd pick for non-browser environments as it is written specifically for browser JS. Even it's object methods have references to conditions only in browsers. Non-browser environments differ greatly in Ecmascript implementation. See how different AS3 is from browser JS, and how up to date and full of functionality it is - and it still is built for the browser - because it has more control of its JS implementation. Server side JS has basically full control of implementation and has to offer so much more then the browser. A lot of the object methods in mootools would be duplication. There are other libraries out there that handle the task better, usually supplied by the same project that develops the JS environment.

    24. David Chambers at 2:29am on March 19, 2010

    That sounds really promising. I'm looking forward to creating an application powered by JavaScript on both the client-side and the server-side, and it sounds as though this'll be more enjoyable than I'd imagined!

    25. betty at 2:47am on May 27, 2010

    thanks for your sharing

    26. design web london at 6:23am on August 6, 2010

    can someone help i want to create a functionality like twitter home page live update ???? Please help

    27. bagsok at 4:30am on November 8, 2010

    good!!! thanks for your sharing

    28. Bangalore website design at 4:18am on February 16, 2012

    Thanks for sharing such a nice post

    29. David Woodfin at 3:20pm on April 30, 2012

    Hi,
    Thank you for your nice article.It is good comment.

    Thanks

    Commenting is now closed. Come find me on Twitter.