What is jQuery .live() event handler

If you did not face with .live() handler before, this post is probably for you!  It makes event handling code much cleaner and easier to use on heavily dynamic pages.

First, lets look into jQuery documentation:

Description: Attach an event handler for all elements which match the current selector, now and in the future.

Most interesting part in this sentence is the end phrase “now and in the future“.

What does it mean?

Very simple and powerful thing! It binds specified event like click to element even if it does not exists yet and would appear later.

This is very handy in AJAX applications. Lets see an example using .click event and then rewrite it using  .live() 

Usage scenario of .live()

Quite often in Rich UI bases on HTML and AJAX some parts of  page are requested from server and inserted into DOM. For example AJAX paging, when user clicks on page number, new table with corresponding records is requested via GET method and inserted into place holder, like this:

Now think that HTML code received from the server has a delete/edit button on each row. To handle these buttons clicks, it is needed to attach .click  handles after content is inserted.

More complex UI adds more mess is in the code.

The .live() way

I rewrote example above using .live() method.

Using this method  no need to bother when code is loaded and inserted into HTML, you always will receive your click event.


Since jQuery version 1.7  documentations says that .live() method is deprecated in favor of new .on method and here is why:

  1. jQuery attempts to retrieve the elements specified by the selector before calling the .live() method, which may be time-consuming on large documents.
  2. Chaining methods is not supported. For example, $(“a”).find(“.offsite, .external”).live( … ); is not valid and does not work as expected.
  3. Since all .live() events are attached at the document element, events take the longest and slowest possible path before they are handled.
  4. Calling event.stopPropagation() in the event handler is ineffective in stopping event handlers attached lower in the document; the event has already propagated to document.
  5. The .live() method interacts with other event methods in ways that can be surprising, e.g., $(document).unbind(“click”) removes all click handlers attached by any call to .live()!

Using .on() make no big difference, here t is:


1 comment

  1. I personally wanted to discuss this particular post,
    “What is jQuery .live() event handler | a32.Blog” cheaphockeyjerseys along with my
    personal buddies on facebook .com. Ijust simply desired
    to distributed ur tremendous writing! Many thanks,

Leave a Reply

Your email address will not be published.