Coding with Jesse

jQuery Live Events

February 16th, 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.


Interested in web development? Subscribe to my newsletter!

Comments

1 . Fred Wu on February 16th, 2009

Fred Wu

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 :) on February 23rd, 2009

:) i :)

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 [email protected]

3 . Jason on February 25th, 2009

Jason

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 on March 2nd, 2009

thijs

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 on March 3rd, 2009

Mauvis

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 on April 23rd, 2009

Thorpe Obazee

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

7 . Dan on May 15th, 2009

Dan

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 on May 15th, 2009

Jesse Skinner

@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 on June 2nd, 2009

Amit Pansare

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

10 . [email protected] Marketing Blog on June 20th, 2009

ZK@Web Marketing Blog

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 on July 7th, 2009

Andreas Kuckartz

So why did I read about LiveQuery recently?!

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

12 . Sean on July 7th, 2009

Sean

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 on July 12nd, 2009

Nikolay

@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 on September 14th, 2009

Julia

@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 on September 14th, 2009

Jesse Skinner

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

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

16 . Marlon on October 28th, 2009

Marlon

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 on October 28th, 2009

Jesse Skinner

@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 on January 27th, 2010

Lerroy

I Love Jquery!

19 . bucabay on March 9th, 2010

bucabay

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 on March 18th, 2010

David Chambers

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

21 . bucabay on March 18th, 2010

bucabay

@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 on March 18th, 2010

David Chambers

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 on March 18th, 2010

bucabay

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 on March 19th, 2010

David Chambers

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 on May 27th, 2010

betty

thanks for your sharing

26 . design web london on August 6th, 2010

design web london

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

27 . bagsok on November 8th, 2010

bagsok

good!!! thanks for your sharing

28 . Bangalore website design on February 16th, 2012

Bangalore website design

Thanks for sharing such a nice post

29 . David Woodfin on April 30th, 2012

David Woodfin

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

Thanks

Comments are closed, but I'd still love to hear your thoughts.