jQuery.live()
function was introduced in jQuery version 1.3. It makes it easy to dynamically bind events to DOM elements that have not yet been created. In other words, it helps you to easily attach events to AJAX loaded elements that match your criteria.
NOTE:
If for some reason you are using old versions of jQuery, prior to 1.3, you will need to use event delegation or another method as they are described in my previous post named “How to bind events to AJAX loaded elements in jQuery 1.2.x”.
So, how does .live()
function works?
It uses event delegation technique to bind to the events that fire on your page. In other words, it binds an event to the DOM tree’s root and listens to all events. When an event is fired it checks it’s originator and checks if we have bound any events to that particular DOM element.
// Example usage of jQuery().live() function $('.mySelector').live('click', function(event){ // my click event handler }); // As of jQuery 1.4.1 .live() can accept // multiple events, just like .bind() does $('input').live('focus blur', function(event){ // fires on focus and blur });
You can also pass in additional data to your events to overcome some issues caused by closure. This was introduced in jQuery 1.4. Also, it worth mentioning that data is passed when the binding is made. Keep this in mind when you pass in dynamic data.
$('.mySelector').live('click', {myVar: 'myVal'}, function(event){ // my click event handler });
NOTE:
Some events were not supported cross browser in jQuery 1.3. Events like submit
were supported in Firefox only. This is resolved in jQuery 1.4. Other methods that were not supported cross browser in jQuery 1.3 include: focusin
, focusout
, mouseenter
, mouseleave
, etc.
NOTE:
.live()
function also works with custom events.
jQuery.live() function performance
Because .live()
uses event delegation and performs additional checks, it will always be slower then events attached to the DOM elements using .bind()
function (this includes shorthands like: .click()
, .submit()
, etc.). However, you can improve your .live()
function performance providing context (as of ver. 1.4).
// Using context for better performance // Note that context is a DOM element, not jQuery $('.mySelector', $('.myParent')[0]).live('click', function(event){ // my faster click event });
Unbinding events attached using .live() function
.unbind()
function equivalent of .live()
function is .die()
. You can unbind ALL events attached using .live()
function from an element by simply calling .die()
. If you want to remove a specific event or a specific handler function of a specific event type, you can call .die('event', functionHandler)
.
// Remove ALL events attached using .live() $('.mySelector').die(); // Remove myFunk() from click event $('.mySelector').die('click', myFunk); function myFunk(){ alert("Clicked!"); }
If you have any questions or need any help, you can ask me on Facebook.