jQuery API

.live()

.live( eventType, handler ) Returns: jQuery

Description: Attach a handler to the event for all elements which match the current selector, now or in the future.

  • version added: 1.3.live( eventType, handler )

    eventTypeA string containing a JavaScript event type, such as "click" or "keydown." As of jQuery 1.4 the string can contain multiple, space-separated event types or custom event names, as well.

    handlerA function to execute at the time the event is triggered.

  • version added: 1.4.live( eventType, eventData, handler )

    eventTypeA string containing a JavaScript event type, such as "click" or "keydown." As of jQuery 1.4 the string can contain multiple, space-separated event types or custom event names, as well.

    eventDataA map of data that will be passed to the event handler.

    handlerA function to execute at the time the event is triggered.

This 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.

Event Delegation

The .live() method is able to affect elements that have not yet been added to the DOM through the use of event delegation: a handler bound to an ancestor element is responsible for events that are triggered on its descendants. The handler passed to .live() is never bound to an element; instead, .live() binds a special handler to the root of the DOM tree. In our example, when the new element is clicked, the following steps occur:

  1. A click event is generated and passed to the <div> for handling.
  2. No handler is directly bound to the <div>, so the event bubbles up the DOM tree.
  3. The event bubbles up until it reaches the root of the tree, which is where .live() binds its special handlers by default.
    * As of jQuery 1.4, event bubbling can optionally stop at a DOM element "context".
  4. The special click handler bound by .live() executes.
  5. This handler tests the target of the event object to see whether it should continue. This test is performed by checking if $(event.target).closest('.clickme') is able to locate a matching element.
  6. If a matching element is found, the original handler is called on it.

Because the test in step 5 is not performed until the event occurs, elements can be added at any time and still respond to events.

See the discussion for .bind() for more information on event binding.

Multiple Events

As of jQuery 1.4.1 .live() can accept multiple, space-separated events, similar to the functionality provided in .bind(). For example, we can "live bind" the mouseover and mouseout events at the same time like so:

$('.hoverme').live('mouseover mouseout', function(event) {
  if (event.type == 'mouseover') {
    // do something on mouseover
  } else {
    // do something on mouseout
  }
});

Event Data

As of jQuery 1.4, the optional eventData parameter allows us to pass additional information to the handler. One handy use of this parameter is to work around issues caused by closures. See the .bind() method's "Passing Event Data" discussion for more information.

Event Context

As of jQuery 1.4, live events can be bound to a DOM element "context" rather than to the default document root. To set this context, we use the jQuery() function's second argument, passing in a single DOM element (as opposed to a jQuery collection or a selector).

$('div.clickme', $('#container')[0]).live('click', function() {
  // Live handler called.
});

The live handler in this example is called only when <div class="clickme"> is a descendant of an element with an ID of "container."

Caveats

The .live() technique is useful, but due to its special approach cannot be simply substituted for .bind() in all cases. Specific differences include:

  • DOM traversal methods are not fully supported for finding elements to send to .live(). Rather, the .live() method should always be called directly after a selector, as in the example above.
  • To stop further handlers from executing after one bound using .live(), the handler must return false. Calling .stopPropagation() will not accomplish this.
  • In jQuery 1.3.x only the following JavaScript events (in addition to custom events) could be bound with .live(): click, dblclick, keydown, keypress, keyup, mousedown, mousemove, mouseout, mouseover, and mouseup.
  • As of jQuery 1.4 the .live() method supports custom events as well as all JavaScript events. As of jQuery 1.4.1 even focus and blur work with live (mapping to the more appropriate, bubbling, events focusin and focusout).
  • As of jQuery 1.4.1 the hover event can be specified (mapping to mouseenter and mouseleave, which, in turn, are mapped to mouseover and mouseout).

Examples:

Example: Click a paragraph to add another. Note that .live() binds the click event to all paragraphs - even new ones.

<!DOCTYPE html>
<html>
<head>
  <style>
  p { background:yellow; font-weight:bold; cursor:pointer; 
      padding:5px; }
  p.over { background: #ccc; }
  span { color:red; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
	<p>Click me!</p>

  <span></span>
<script>
    $("p").live("click", function(){
      $(this).after("<p>Another paragraph!</p>");
    });
</script>

</body>
</html>

Demo:

Example: To display each paragraph's text in an alert box whenever it is clicked:

$("p").live("click", function(){
  alert( $(this).text() );
});

Example: To cancel a default action and prevent it from bubbling up, return false:

$("a").live("click", function() { return false; })

Example: To cancel only the default action by using the preventDefault method.

$("a").live("click", function(event){
  event.preventDefault();
});

Example: Can bind custom events too.

<!DOCTYPE html>
<html>
<head>
  <style>
  p { color:red; }
  span { color:blue; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
	<p>Has an attached custom event.</p>
  <button>Trigger custom event</button>
  <span style="display:none;"></span>
<script>

    $("p").live("myCustomEvent", function(e, myName, myValue){
      $(this).text("Hi there!");
      $("span").stop().css("opacity", 1)
               .text("myName = " + myName)
               .fadeIn(30).fadeOut(1000);
    });
    $("button").click(function () {
      $("p").trigger("myCustomEvent");
    });

</script>

</body>
</html>

Demo:

Comments

  • Support requests, bug reports, and off-topic comments will be deleted without warning.

  • Please do post corrections or additional examples for .live() below. We aim to quickly move corrections into the documentation.
  • If you need help, post at the forums or in the #jquery IRC channel.
  • Report bugs on the bug tracker or the jQuery Forum.
  • Discussions about the API specifically should be addressed in the Developing jQuery Core forum.
  • Foo
    $('input').not('.no_change').live('change', function(){..});

    Live in combination with not doen't seem to work here.
  • That's right. Please see the Caveats section above.
  • You should use delegate instead. Delegate works with .not, .parent, .children, etc.
  • Curious
    I am wondering whether there is a remedy for IE8 not accepting "change" within "live()". Do I need to go back to "livequery"?
  • I had issues in IE8 with 1.4.2 and live/change as well. I switched to using delegate instead of live and my problems went away.
  • I was under the impression that .live() events would progagate. However, when I use this:

    $('*').live('click', function() {
    console.log(this);
    });

    and click on an li nested inside a ul (in turn inside body, html), I only see a single log line for the original li. What gives?
  • Live doesn't seem to work on a newly created anchor tag. Look at my example here: http://jsbin.com/udera/

    If I use bind, it works perfectly... What's the big difference?
  • jfb
    I have exactly the same problem... Is it a bug ?
  • I don't want to be too hasty in my conclusions, but it looks like a bug, smells like a bug and acts like a bug....

    Just to be sure I edited my jsbin.com example. Now it uses jQuery 1.4.2 instead of just "jQuery latest". Thisway we can establish if it is a 1.4.2 bug or not. New link: http://jsbin.com/udera/5
  • Have a look at the first bullet in the Caveats section above.
    It says "... the .live() method should always be called directly after a selector".
    Your example should work if you select the anchor explicitly after creating it.
  • Dima
    It appears that $(selector).live() has to actually evaluate the selector and perform a DOM query before attaching the handler to the root, which seems kinda wasteful, especially when the selector is complex, and/or matches many elements, since, the result of the query is nor really needed.
    Wouldn't it be better and more useful if the semantics was more along the lines of
    $(context).live(selector, event, handler), so that one could do something like
    $(document).live(".button", "click", handleClick) without having to find all the buttons on the page?

    For the time being, I find it better to just use
    $(document).bind('click', function(e) { if($(e.target).is(.button)) handleClick(e); });
    instead of .live() for the effectiveness.
  • Maybe sometimes. That's why we have the .delegate() method.
  • Dima
    So, what exactly is the advantage of .live() over .delegate()?
    Or rather when exactly is it advantageous to use .live() rather than .delegate()?
  • .live() just gives you a nicer syntax. .delegate() is always more efficient.
  • It seems there are some issues in IE8 and jQuery 1.4.2 regarding live() and drag'n'drop events;

    1. IE8 doesn't throw "dragend" events when using live() as the other browsers. It does work when using bind() though.

    2. IE8 doesn't allow drops when using live() on the drop target, the other browsers do. It does work when using bind() though.

    Will report this in the bug tracker if not already reported. (Test case available at http://homepage.mac.com/matias/jquery/bug-live-... )

    UPDATE: I created a ticket at http://dev.jquery.it/ticket/6578
  • I'm experiencing the same bugs: the events for "dropable" elements (dragenter, dragover, dragleave, drag) are not triggered by IE8 (not tested for the previous versions sorry); though it works on all other major browsers (FF, Chrome, Safari, Opera 10.60 doesn't support native 'drag and drop') and on IE9 preview (v.9.0.7916.6000)
  • Triple3
    Is there any way to UNBIND something attached with the live method? I'm actually using live to attach an event but later want to remove the event but it doesn't seem to remove. I'm not sure if it's removing and the live previously called to add it is readding it or it simply won't remove.

    Thanks
  • sure is. die();

    http://api.jquery.it/die/
  • flamingsevens
    I had hoped that in your last example( ... "can bind custom events too") that you would have demonstrated how to trigger the live method using values for myName and myValue. I have a similar problem that I am working on and I am having trouble passing values to the live method using a custom event.
  • flamingsevens
    Sorry, was able to find a link under the trigger documentation. I see that it would be coded as follows: $("p").trigger("myCustomEvent", ['value1', 'value2']);
Time to generate: 1.89485