jQuery.live()

Mar11
Missing Image
By SiteCrafting Staff

jQuery 1.3 has added support for live events, and it makes developing a breeze. Before, you'd have to wait until the page is completely loaded to add events to elements. And if you added new elements to the page, they would need special attention to have events added. Not anymore!

  jQuery has become my favorite toy in web dev. And my latest favorite feature is live events (added in jQuery 1.3). Live events are a way of adding events to a CSS selector. If an event occurs to something that fits that selector, the event handler is fired. In layman speak, you can setup events like you can setup style sheets.

jQuery live looks like this:
$({selector}).live({event}, {handler})

An example would be creating a button that self-replicates.

$('button').live('click', function(){ $(this).after($(this).clone()); });

Now, every button on a page will insert a new button just after itself. While this isn't very useful, you will notice that the new click event is fired without adding extra event handlers. This is very useful when you are doing a lot of ajax manipulation; You can just set an initial event handler to a selector and it will automatically replicate out all new elements.

Another important implication worth mentioning is that you no longer have to wait until the page has loaded to assign events. Before, you had to wait until the document has loaded an element so JavaScript would know what the event handler was for. But now, timing doesn't matter; Event handlers can be added to CSS selectors in the head.

I'm excited to see where this will take us in JavaScript development. Let us know if you've used jQuery Live in any interesting places!


Dev

Back To Feed