140

I have read the documentation of each function on jQuery official website, but there is no such comparison listings between below functions:

$().click(fn)
$().bind('click',fn)
$().live('click',fn)
$().delegate(selector, 'click', fn)
$().trigger('click') // UPDATED
$().on('click', selector ,fn); // more UPDATED

Please avoid any reference link.

How do all above functions exactly works and which should be preferred in which situation?

Note: If there are any other function(s) having the same functionality or mechanism, Then please elaborate.

Update

I have also seen a $.trigger function. Does it work similar to the above functions?

More Update

Now .on is added in v1.7 and I think this one somehow cover all of above functions requirement together.

6
  • 3
    @I Like PHP, sometimes people vote things down if they don't feel it's a question that couldn't be answered by a manual or appears to be a homework question. don't worry, other people will vote it up if they find it useful. Jun 2, 2010 at 4:18
  • @Typeoneerror--Thanks for support, i already read the manual and when i didn't understand the clear difference then i post here.
    – xkeshav
    Jun 2, 2010 at 4:22
  • 3
    @I Like PHP - Edited the question for a bit of cleanup...this is often asked but rarely in this way, it can easily be a valuable google-able resource. I agree a wiki-ish entry of something like this would be very helpful, I see confusion around this, especially with .live() and .delegate() almost every day, +1 for a perfectly valid question. Jun 2, 2010 at 10:21
  • @Nick Craver Thanks for editing, actually i m bad in english(lol). is there any maunal/ reference that how do we post a question on SO. ot it just came by experience
    – xkeshav
    Jun 2, 2010 at 11:05
  • @I Like PHP - It's a bit of both, there's a great all-around FAQ for SO here: meta.stackexchange.com/questions/7931 For the phrasing/comments, you just start to learn what fits and is the best way to convey your thoughts, code > any description sometimes, using the right keyword, tagging appropriately, just comes the longer you're here I suppose, I see lots of posters improving over time. As for your edit, .trigger() just invokes the event handler...I'll add a description to my answer below. Jun 2, 2010 at 12:01

5 Answers 5

163

Before you read this, pull this list of events up in another page, the API itself is tremendously helpful, and all of what I'm discussing below is linked directly from this page.

First, .click(function) is literally a shortcut for .bind('click', function), they are equivalent. Use them when binding a handler directly to an element, like this:

$(document).click(function() {
  alert("You clicked somewhere in the page, it bubbled to document");
});

If this element gets replaced or thrown away, this handler won't be there anymore. Also elements that weren't there when this code was run to attach the handler (e.g. the selector found it then) won't get the handler.

.live() and .delegate() are similarly related, .delegate() actually uses .live() internally, they both listen for events to bubble. This works for new and old elements, they bubble events the same way. You use these when your elements may change, e.g. adding new rows, list items, etc. If you don't have a parent/common ancestor that will stay in the page and not be replaced at any point, use .live(), like this:

$(".clickAlert").live('click', function() {
  alert("A click happened");
});

If however you do have a parent element somewhere that isn't getting replaced (so its event handlers aren't going bye bye) you should handle it with .delegate(), like this:

$("#commonParent").delegate('.clickAlert', 'click', function() {
  alert("A click happened, it was captured at #commonParent and this alert ran");
});

This works almost the same as .live(), but the event bubbles fewer times before being captured and the handlers executed. Another common use of both of these is say your class changes on an element, no longer matching the selector you originally used...with these methods the selector is evaluated at the time of the event, if it matches, the handler runs...so the element no longer matching the selector matters, it won't execute anymore. With .click() however, the event handler is bound right on the DOM element, the fact that it doesn't match whatever selector was used to find it is irrelevant...the event is bound and it's staying until that element is gone, or the handler is removed via .unbind().

Yet another common use for .live() and .delegate() is performance. If you're dealing with lots of elements, attaching a click handler directly to each element is expensive and time consuming. In these cases it's more economical to setup a single handler and let bubbling do the work, take a look at this question where it made a huge difference, it's a good example of the application.


Triggering - for the updated question

There are 2 main event-handler triggering functions available, they fall under the same "Event Handler Attachment" category in the API, these are .trigger() and .triggerHandler(). .trigger('eventName') has some shortcuts built-in for the common events, for example:

$().click(fn); //binds an event handler to the click event
$().click();   //fires all click event handlers for this element, in order bound

You can view a listing including these shortcuts here.

As for the difference, .trigger() triggers the event handler (but not the default action most of the time, e.g. placing the cursor at the right spot in a clicked <textarea>). It causes the event handlers to occur in the order they were bound (as the native event would), fires the native event actions, and bubbles up the DOM.

.triggerHandler() is usually for a different purpose, here you're just trying to fire the bound handler(s), it doesn't cause the native event to fire, e.g. submitting a form. It doesn't bubble up the DOM, and it's not chainable (it returns whatever the last-bound event handler for that event returns). For example if you wanted to trigger a focus event but not actually focus the object, you just want code you bound with .focus(fn) to run, this would do that, whereas .trigger() would do that as well as actually focus the element and bubble up.

Here is a real world example:

$("form").submit(); //actually calling `.trigger('submit');`

This would run any submit handlers, for example the jQuery validation plugin, then try to submit the <form>. However if you just wanted to validate, since it's hooked up via a submit event handler, but not submit the <form> afterwards, you could use .triggerHandler('submit'), like this:

$("form").triggerHandler('submit');

The plugin prevents the handler from submitting the form by bombing out if the validation check doesn't pass, but with this method we don't care what it does. Whether it aborted or not we're not trying to submit the form, we just wanted to trigger it to re-validate and do nothing else. (Disclaimer: This is a superfluous example since there's a .validate() method in the plugin, but it's a decent illustration of intent)

6
  • Very thorough. One small correction: trigger does not fire a native event. By native I mean an event simulated with fireEvent (IE) or dispatchEvent (w3c). Jun 2, 2010 at 16:56
  • @Crescent - Updated to be less ambiguous, I meant that it fires the native event actions, like forms submission, link following etc... hopefully the update is clearer :) Jun 2, 2010 at 17:44
  • @Nick from what I'm reading, it seems like your take on live() is different from the one you gave me here: stackoverflow.com/questions/3981762/… Is 'weight' still a concern when using live()?
    – Yahel
    Jul 11, 2011 at 6:03
  • @yahelc - Yes, of course...this answer is strictly comparing the options of event handlers and their specific purpose. The weight cost vs. number of initial bindings vs. if you're adding anything dynamically vs. the initial selector are all still valid concerns. If you're page structure isn't that big you you don't have that many events then you're fine...the concern over weight is directly proportional to the size/depth of your structure and the number of events (of the type your .live() call listens for, e.g. click) that are being generated, since it runs selectors for each one. Jul 11, 2011 at 9:40
  • 1
    in jQuery 1.7, live() is deprecated in favour of $(document).on().
    – Synchro
    Nov 23, 2011 at 13:08
28

The first two are equivalent.

// The following two statements do the same thing:
$("blah").click( function() { alert( "Click!" ); } );
$("blah").bind( "click", function() { alert( "Click!" ); } ); 

The second one, though, can be used to bind to more than one event at the same time, by specifying several space-separated event names:

$("blah").bind( "click mouseover mouseout", function() { alert( "Click! Or maybe mouse moved." ); } ); 

The .live method is more interesting. Consider the following example:

<a class="myLink">A link!</a>
<a id="another">Another link!</a>

<script>
    $("a.myLink").click( function() { alert( 'Click!' ); } );

    $("a#another").addClass( "myLink" );
</script>

After the second line of the script executes, the second link will also have a CSS class of "myLink". But it will not have the event handler, because it didn't have the class when the event was attached.

Now consider you wanted it to be the other way around: every time a link with class "myLink" appears somewhere on the page, you want it to have the same event handler automatically. This is very common when you have some kind of lists or tables, where you add rows or cells dynamically, but want them all to behave in the same way. Instead of going to all the pain of assigning event handlers anew every time, you can use the .live method:

<a class="myLink">A link!</a>
<a id="another">Another link!</a>

<script>
    $("a.myLink").live( "click", function() { alert( 'Click!' ); } );

    $("a#another").addClass( "myLink" );
</script>

In this example, the second link will also get the event handler as soon as it gets the "myLink" class. Magic! :-)

Of course, it's not that literal. What .live really does is attach the handler not to the specified element itself, but to the very root of the HTML tree (the "body" element). Events in DHTML have this funny feature of "bubbling up". Consider this:

<div> <a> <b>text</b> </a> </div>

If you click on "text", then first the <b> element will get a "click" event. After that, the <a> element will get a "click" event. And after that the <div> element will get a "click" event. And so on - all the way up to the <body> element. And that's where jQuery will catch the event and see if there are any "live" handlers which apply to the element that caused the event in the first place. Neat!

And finally, the .delegate method. It simply takes all the children of your element that conform to the given selector and attach a "live" handler to them. Take a look:

$("table").delegate( "td", "click", function() { alert( "Click!" ); } );

// Is equivalent to:
$("table").each( function() {
    $(this).find( "td" ).live( "click", function() { alert( "Click!" ); } );
} );

Questions?

3
  • To be accurate, .live() binds to document not <body> :) You can view a demo here, just pull up the console to inspect: jsfiddle.net/aJy2B Jun 2, 2010 at 4:24
  • 3
    It was more convenient to explain it this way. :-) Jun 2, 2010 at 4:33
  • 4
    Fair enough on the "body" part, but "all the way up to the <body> element" is wrong, events continue to bubble past there, and it's not where .live() handlers live, it's above that, on document :) You can see a demo of this here: jsfiddle.net/S2VBX Jun 2, 2010 at 4:39
8

As of jQuery 1.7, the .live() method was deprecated. If you are using a jQuery version < 1.7 than it is officially recommended to use .delegate() over .live().

.live() has now been replace with .on().

Best to go directly to the jQuery site for more information, but here are the current versions of the .on() method:

.on( events [, selector] [, data], handler(eventObject) )
.on( events-map [, selector] [, data] )

http://api.jquery.com/on/

0
2

$().click(fn) and $().bind('click', fn) are identical at first sight, but the $.bind version is more powerful for two reasons:

  1. $().bind() allows you to assign one handler to multiple events, for example, $().bind('click keyup', fn).
  2. $().bind() supports namespaced events - a powerful feature if you want to remove (unbind) only certain event handlers that an element is bound to - read more in Namespaced Events.

Live vs delegate: this has already been answered in the other replies.

1

This is where reading the API might help. However, I know off the top of my head, so you can continue being lazy (yay!).

$('#something').click(fn);
$('#something').bind('click',fn);

There's no difference here (that I know of). .click is simply a convenience/helper method to .bind('click'

// even after this is called, all <a>s in
// <div class="dynamic_els"> will continue
// to be assigned these event handlers

$('div.dynamic_els a').live(‘click’,fn);

This is very different, as .live adds events to the selector you pass in (which you haven't here) and continues to look at the DOM as nodes are inserted / removed

$('#some_element').delegate('td','click',fn);

This is only different because of the way you're assigning event handlers. .delegate is centered on DOM event bubbling. The basic principle is that every event bubbles upward through the DOM tree until it reaches the root element (document or window or <html> or <body>, I can't remember exactly).

Either way, you're binding an onclick handler to a all the <td>s within $('#some_element') (you must specify a selector, though you could say $(document)). When one of its children is clicked, the event bubbles up to the <td>. You can then extract the source element of the event (which jQuery does for you automagically).

This is useful when there are tons of elements and you only have only a few (or one central) point[s] that these events will go through. This saves the browser effort and memory to consolidate these event handlers into less objects.

1
  • 1
    .live() also works off event bubbling, in fact .delegate() is a wrapper for .live(), it's just adding a context and binding to an element other than document to capture the bubbles. I think your understanding of how the bubbling handlers work is a bit off (this is the most commonly misunderstood aspect of jQuery 1.4 I think). The handler is only on the element you bound it to, so whatever element you called .delegate() on, or document in the case of .live(), when an event bubbles to there, it checks the target to see if it matches the selector, and if so executes. Jun 2, 2010 at 4:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.