jQuery edge delegate method has arrived

Neeraj Singh

By Neeraj Singh

on February 2, 2010

One of the issues with live method is that live method first searches through all the elements then throws away the result.

1$('p').live('click', function({})

In the above case jQuery does nothing with the selected p elements. Since the result does not really matter, it is a good idea to remove such codes from the document ready callbacks list.

So instead of doing this

1$(function(){
2  $('p').live('click', function({})
3})

just do this

1$('p').live('click', function({})

Going a step further

John just landed this commit which adds delegate method .

Html markup

1<div id="lab">
2  <p>p inside lab</p>
3</div>
4<p>p outside lab</p>

If you want to track all the clicks on p then you could write like this.

1$(document).delegate("p", "click", function () {
2  log("p was clicked");
3});

However if you only want to track clicks on 'p' which are inside the id lab then you can write like this.

1$("#lab").delegate("p", "click", function () {
2  log("p was clicked");
3});

Note this functionality is in jQuery edge and is not available in jQuery 1.4.1. So you will have to get jQuery code from github to play with it.

If you are interested in the jQuery.live vs jQuery.fn.live discussion then follow this thread .

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.