I’m sure anyone that has developed in javascript has had monumental headaches over the years trying to write code that allows event handlers to operate on dynamically created elements. The main problem I always seem to come across is assigning event handlers to elements that are generated after the page has loaded. jQuery 1.2.x went some way to solving this by adding the bind and unbind events. Even with this functionality, you still had to manually bind an event handler to every new element and it seemed like a lot of work to achieve something relatively simple. These days people are coding fluid interfaces and letting javascript do a lot of the heavy lifting and dynamic element creation in javascript is a big part of the web at the moment.
The example below shows how bind() events are added to individual elements. Every time a button with the class ‘myButton’ is clicked, a link is added to the container div. Because the links do not exist when the page is created, the event handlers have to be created after each element using the bind method.
$('.myButton').click(function() {
$('#myContainer').append('<a class="myElement">Click me</a>');
$('.myElement').bind('click', function(){
clickFunction();
return false;
});
});
function clickFunction() {
// do something here with the click
alert('This link has just been clicked!');
}
Thankfully jQuery 1.3 has introduced the live() and die() events. By using the live() method, it is possible to assign an event handler to a selector, even if the element doesn’t exist. If the element is created in the future, the event handler will be automatically added to it. The example below will create a click event handler on any element with the class ‘myElement’ regardless if it exists or not.
$('.myElement').live('click', function() {
clickFunction();
});
This example doesn’t really cut down on code but it does mean you can forget about tracking the event handlers. Just assign once and forget. Bugs won’t appear in your code just because you forgot a bind() function somewhere and every subsequent ‘myElement’ element that is created will have an event handler assigned to the click event.
This has already saved me considerable time banging my head against the screen. All hail the live() event! One thing I have noticed is there is a slight performance issue when using the live event as oppose to using the bind functions so you have to weigh up the pro’s and cons of using it in javascript intensive applications.
