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"

    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"

    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, then the message gets printed. 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.
  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.

Caveats

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

  • 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). Additionally, as of jQuery 1.4.1 the hover event can be specified (mapping to "mouseenter mouseleave"). In version 1.3.x, however, 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.
  • 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.
  • See the discussion for .bind() for more information on event binding.

    As of jQuery 1.4.1 you can also pass in multiple events to live, similarly to the functionality provided in .bind().

    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.

    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.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.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.
    • In 1.3.2 in a specific application, I found that by changing the event from "blur" to "change" for the event, I got it live() working in place of bind() in Firefox. But I don't see "change" in the list of acceptable events in the caveats paragraph above. Is that an oversight or am I likely to hit a problem in a different browser?
    • sunrayravi
      live function doesnt trigger change events in a select box in IE7. Is this a bug or the expected behaviuor?? It work fines in FF and chrome?
    • Does .Live() support namespaced events? I'm not having problems when I .bind("click.namespace", handler), but I cant seem to get the same thing to work with .live("click.namespace", handler). I don't know if this is a bug or just not supported. Thanks!
    • Remus
      When using live() with the "change" event, if the initial value of the element bound to is nothing (element is empty) and you type in a value, the event does not trigger as it should. It only triggers if there is an initial value in there or if the value is changing (duh!) but not when the value is empty and you put a value in for the first time.

      Is this a bug or should I use a different event to capture even the first "change", from empty to a non-empty value?
    • buymeasoda
      Hi,

      Could you please update the docs and examples to include details of the new ability to use a context with the live() event.

      It was mentioned in the release notes during 14 days of jQuery, but I can't see it presented here in any detail.

      From: http://jquery14.com/day-01/jquery-14

      live/die now work with context (Commit)

      You can now specify a context to the selector that will be used to bind a live event. If you do, only elements under that context will be bound. While the elements themselves do not need to exist when you create the live event, the context must exist.
    • adardesign
      why does .live() not work when its being called on a cached DOM element

      like :
      var myDiv = $("<div/>").addClass("justATest").html(someCahchedHTML)
      myDiv.live("click", function(){alert("this will not be fired")})
    • Because .live() should be called on selectors, not on the elements. Freshly created and even not yet attached nodes have not selectors
    • adardesign
      Thanks, and how about a cached selector?

      like
      var allMylinks = $("a");
      allMylinks.live("click", function(){
      console.log("logs nothing")
      })
    • scurvysquid
      The documentation states that .stopPropagation() will not have the intended effect with live-bound events, but I've found that by checking .isPropagationStopped() you can get around this.

      I have nothing against returning false from my functions but if for some reason you like for the return type of your functions to be something else, you can currently use .isPropagationStopped() correctly in the binding on the ancestor element that you do not wish to be triggered.

      Does anybody know if this functionality is intended, something that we can rely on, and recommended?
    • michelypma
      It looks like the multiple events in the live method as mentioned by Paul Irish (http://jquery14.com/day-05) doesn't work as you expect:
      $('div.hoverbox').live('mouseenter mouseleave',function(e){

      var isEnter = (e.type === 'mouseenter');

      $(this).css('backgroundColor', isEnter ? 'red' : 'blue');

      });

      When i use this code for example:

      $('a[title]').live('mouseenter mouseleave',function(e){
      var isEnter = (e.type === 'mouseenter');
      $(this).css('backgroundColor', isEnter ? 'red' : 'blue');
      });

      It ignores my a[title] selector and triggers the event on all DOM elements...
      But if i use 1 event instead:
      $('div.hoverbox').live('mouseenter',function(e){

      var isEnter = (e.type === 'mouseenter');

      $(this).css('backgroundColor', isEnter ? 'red' : 'blue');

      });

      When i use this code for example:

      $('a[title]').live('mouseenter mouseleave',function(e){
      var isEnter = (e.type === 'mouseenter');
      $(this).css('backgroundColor', isEnter ? 'red' : 'blue');
      });

      It works like a charm....
      Seems to me like a bug?