jQuery’s .delegate()

This weekend I saw a really good talk by John Resig on the .delegate() function in jQuery. It allows you to apply one event to the parent element rather than applying multiple functions to several children elements.  This can be very useful for a number of reasons.  Traditionally I’ve used the .bind() method for adding events to my code, but .delegate() gives you the ability to listen to new elements added to the page.  This has be very helpful for projects that are more ajax based where I have new elements created at run time.  I’m no longer setting and resetting events!

The Javascript

In the example provided in the jQuery documentation they use a case where you would have multiple table cells nested within a table element.  The beauty of this is you apply the event one time rather than once for each child node.

$("table").delegate("td", "hover", function(){
	$(this).toggleClass("hover");
});

If you look at my CSS3 Chessboard example this would be a great way to add the drag/drop support and also save me from looping through all my elements.  I’m still working with the function and trying to do some speed tests to see how much this can save on performance.  If you have any tips post them in the comments.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>