Monday, January 19, 2009

Live and Die with jQuery

jQuery is a JavaScript library that makes web programming simple and highly productive. With the new 1.3 release, jQuery now supports live and die events. To understand live and die events, we must recollect how things were done before the 1.3 release. To bind events to elements we used jQuery's bind method.

$("input:type=button").bind("click", function() {

The code above binds the click event to all buttons on the page. However, there is one major drawback to using the bind method. Any buttons dynamically added to the page in the future must be individually bound with the click event. Hence, bind only works on the set of elements currently in the DOM.

live overcomes this drawback and binds to elements currently present and also ones added in the future. The syntax for live is similar to bind. The code below binds the click event to all buttons currently on the page and even ones added in the future.

$("input:type=button").live("click", function() {

die is the opposite of live. To unbind all events previously bound with live we use the die method.


No comments: