Using jQuery to Attach Events to Future Elements

I’m sure most jQuery users are familiar with the various methods used to attach event handlers (such as “onclick”, “onchange”, etc.) to elements that already exist on the page, but many probably aren’t aware that you can have jQuery automatically add those event handlers to any future elements, too.

If you’re like me, you probably tried simply building the event binders into the functions that create the elements, similar to the following:

$("#myDiv").append("<a href='test' class='myclass'>This is a new link</a>");
$("#myDiv a.myclass").click(function() { doSomething(); });

However, that code is extremely clunky, and, the way it’s written above, will cause jQuery to cycle through all of the links with a class of “myclass” each time you add a new one.

Recent versions of jQuery, however, offer two solutions that perform the work for you. These methods are delegate() and live(). The first, delegate(), allows you to specify a selector, and automatically bind an event to all current and future children that match a selector you feed to the method. For instance, if you want all current and future links that are contained within #myDiv to execute a function when clicked, you would use something like:

$("#myDiv").delegate("a","click",function() { doSomething(); });

The other option is the live() method. The live() method allows you to simply bind an event handler to the specified selector. It’s very similar to the delegate() method, except that it acts on the jQuery object you specify in the initial selector rather than acting on the child selector you supply as part of the function call. Therefore, to do something similar to what I showed above, you would use the following code:

$("#myDiv a").live("click",function() { doSomething(); });

Post Your Comment

Your email address will not be published.