18 April 2010 ~ 1 Comment

.live() and the future

Just recently i seen this used by a co-worker, and did not know much about this. So I took some time and looked it up on the jQuery site docs. I was amazed by what it does, the .live() function will match any element now and in the future! This means if you .load() a remote page in the .live() can match an element on that page as it’s loaded in!

Attach a handler to the event for all elements which match the current selector, now or in the future. jQuery – .live()

Some info on .live()
his method is a variation on the basic .bind() method for attaching event handlers to elements. When .bind() is called, the elements that the jQuery object refers to get the handler attached; elements that get introduced later do not, so they would require another .bind() call. For instance, consider the HTML:

<body>
  <div class="clickme">
    Click here
  </div>
</body>

We can bind a simple click handler to this element:

$('.clickme').bind('click', function() {
  // Bound handler called.
});

When the element is clicked, the handler is called. However, suppose that after this, another element is added:

$('body').append('<div class="clickme">Another target</div>');

This new element also matches the selector .clickme, but since it was added after the call to .bind(), clicks on it will do nothing.

The .live() method provides an alternative to this behavior. If we bind a click handler to the target element using this method:

$('.clickme').live('click', function() {
  // Live handler called.
});

And then later add a new element:

$('body').append('<div class="clickme">Another target</div>');

Then clicks on the new element will also trigger the handler.

Tags: ,

One Response to “.live() and the future”

  1. eggheadreport 18 April 2010 at 1:04 am Permalink

    cool stuff man. great post.