jQuery Live Event

jquery-live-functionI love jQuery. I have expressed my love for jQuery here, here and here and still I feel so much for it. Also check out the 20 jQuery Tips & Tricks Tutorial.

Let us see a wonderful function available in jQuery which many of us don’t know. Most common use of jQuery is to attach an event some callback function to any element on webpage.

When we attach any event to element on webpage using normal functions such as mouseclick or click or mouseover, it attach the event only to current elements. If dynamically we add another element in future then this handler is not attached to those dynamic elements.

For example, we have a button on click of which we display an alert message. We can use $('#buttonid').click() to attach a handler function which can display alert message. But what if we dynamically add another button on page and we want exactly the same functionality? Well, jQuery Live Function comes to rescue for such requirements.

Let us see an example of normal event handling and one with Live function. In this example, we are dynamically adding list items that has hover effect. When mouse is hover on this list item, it changes the color. We will do this by both traditional way and using Live function.

The HTML

Following is the HTML Code for our example:

<TABLE>
<TR valign="top">
	<td>
	<input type="button" value="Click To Add (without Live)" id="add"/>
	<ul id="list" class="list">
		<li>&nbsp;</li>
		<li>&nbsp;</li>
		<li>&nbsp;</li>
		<li>&nbsp;</li>
	</ul>
	</td>
	<td>
	<input type="button" value="Click To Add (with Live)" id="addLive"/>
	<ul id="listLive" class="list">
		<li>&nbsp;</li>
		<li>&nbsp;</li>
		<li>&nbsp;</li>
		<li>&nbsp;</li>
	</ul>
	</td>
</TR>
</TABLE>

The HTML will display two buttons and two list sets. One button will dynamically add list item to one list using normal click event, where as another button will use Live events to do this.

The CSS

We will use following CSS in our example:

.list	li 	{ 
	list-style: none; 
	background-color:#eeffaa; 
	width:150px; 
	margin-top:5px; 
	border:1px solid #8AAC00; 
}

.list li.selected { 
	background-color: #ffaaee; 
}

The jQuery

First we will attach an event with two buttons to dynamically add a list item.

$('#add').click(function(){
	$('#list').append('<li>&nbsp;</li>');
});
$('#addLive').click(function(){
	$('#listLive').append('<li>&nbsp;</li>');
});

Then, we will make the first list hoverable using mouseover and mouseout event.

$('#list>li')
		.mouseover(function(){ $(this).addClass('selected'); })
		.mouseout(function(){ $(this).removeClass('selected'); });

And, then we will make the second list hoverable using live() event.

$('#listLive>li')
	.live('mouseover', function(){ $(this).addClass('selected');   })
	.live('mouseout',  function(){ $(this).removeClass('selected'); });

Notice the difference in above code. In first snippet we are using mouseover and mouseout functions to attach events with handlers to change the background color of list item. When we add a list item dynamically, this handler are not attached to newly created list item. And in second snippet we are using live() to attach event mouseover and mouseout.

This way we ensure that any dynamically added element will have the events handler attached with them.
jQuery 1.3 and below
Currently jQuery 1.3 and below is not supporting events blur, focus, mouseenter, mouseleave, change, submit.
But the good news is that jQuery 1.4 alpha 1 has just been released which supports these events.

Important Points

Following are few important points one should note before working with Live events.

  • When you bind a “live” event it will bind to all current and future elements on the page.
  • Live events do not bubble in the traditional manner and cannot be stopped using stopPropagation or stopImmediatePropagation.
  • Live events currently only work when used against a selector. For example, this would work: $("li a").live(...) but this would not: $("a", someElement).live(...) and neither would this: $("a").parent().live(...).
  • .live doesn’t support the no-event style callback that liveQuery provides. Only event handlers can be bound with .live.
  • .live doesn’t have a “setup” or “cleanup” step, since all events are delegated rather than bound directly to an element.
  • To remove a live event you should use the die() method

Live Demo

Following is the live demo for jQuery Live Event Example.

Click To View Demo
Download Source Code

Get our Articles via Email. Enter your email address.

You may also like...

10 Comments

  1. Hi,
    U have a nice post!
    It is so interesting and realistic !
    Thanks for sharing !

  2. indialike says:

    Very nice and useful tutorials to web designers,
    Thanks for posting.

  3. SMiGL says:

    Excelent example

  4. Mustinet says:

    we can do it with .clone(true) function

  5. tony says:

    Great post . I encounter a problem with live event.
    The senario is like this .I am using displaytag inside a jquery tab , displaytag generate a dynamic navigation link bar , when I click the link , the page refreshed .
    So , I want to control the link and change the link to go through my adapter function to do an ajax load without page refresh.
    Cause the links are generated dynamically , so I want to bind them to live event .
    $(“pagelinks a[‘href*=page’]”).live(‘click’ , function () { // do somethings });
    The problem is the selector returns a collection , do I need to bind a collection of similar tag to live events ? This is no any difference to bind them to click directly through .each loop.

  6. nitin says:

    hey very nice article.
    i was very confused with live in sense what exactly its use is.
    this article made the picture clearer.
    thanks.

  7. Arun Kumar A B says:

    Nice tutorial

  8. yep, when i first learnt jquery i had problem on binding event in dynamically added elements.
    people at stackoverlfow.com helped me a lot.
    And here you share the knowledge
    hope more people will understand this concept.

    System.out.println("You Rock :D");
    
  9. Afdhh says:

    Hi

  10. Shalu says:

    Thanks for very clearly explaining the ‘Live’ event. Enjoyed reading it!

Leave a Reply

Your email address will not be published. Required fields are marked *