47

I'm using jQuery in my web application. I've been using .bind() but I see that it is a little slow, so while reading the documentation I read about .on() and .delegate(). I understand how .delegate() works but I’m not clear on what is the difference between it and .on() or which is better in which scenarios.

Also I'm using jQuery 1.6 so I would like to know if it is worth it to prepare my script for jQuery 1.7 by putting in a condition similar to the following:

if(typeof $(selector).on == 'function'){
    /* use .on() */
}else{
    /* use .delegate() */
}

Is this a good idea (to prepare for .on()) or is it just looking for trouble for nothing?

Please help me to get clear understanding of these methods.

Jack
  • 10,943
  • 13
  • 50
  • 65
Galled
  • 4,146
  • 2
  • 28
  • 41

6 Answers6

53

The .on() syntax is the new syntax that version 1.7 uses and it is meant to substitute .bind(), .delegate() and .live().

More here -> http://blog.jquery.com/2011/11/03/jquery-1-7-released/

New Event APIs: .on() and .off()

The new .on() and .off() APIs unify all the ways of attaching events to a document in jQuery — and they’re shorter to type!

  $(elements).on( events [, selector] [, data] , handler );
  $(elements).off( [ events ] [, selector] [, handler] );

When a selector is provided, .on() is similar to .delegate() in that it attaches a delegated event handler, filtered by the selector. When the selector is omitted or null the call is like .bind(). There is one ambiguous case: If the data argument is a string, you must provide either a selector string or null so that the data isn’t mistaken as a selector. Pass an object for data and you’ll never have to worry about special cases.

All the existing event binding methods (and their corresponding unbinding methods) are still there in 1.7, but we recommend that you use .on() for any new jQuery project where you know version 1.7 or higher is in use. (emphasis mine)

lalibi
  • 3,057
  • 3
  • 33
  • 41
  • so, no more confusion with `delegate()` we can just use `on()` for now on? – Sisir Dec 11 '13 at 09:47
  • @Sisir yes, `delegate()` is now deprecated – lalibi Dec 11 '13 at 10:27
  • I love one of excess of delegate, that we can see he function handler works for now and future. So we don't need to re-call the event handler just like `.on()` for outputted data(elements) from AJAX (for example) – Aldi Unanto Dec 16 '14 at 04:20
  • **Update:** "All the existing event binding methods ... are still there" - no, **`.live()`** was being removed since **Jquery 1.9.x**. So it is no longer available. – Matt Aug 29 '17 at 07:29
11

I recently answered a related question about this very topic.

The important part is:

The new ondocs function is used to replace the existing separate methods of binding events:

The existing events continue to exist, and are simply aliases of on. There is no official report to suggest that they will be removed, so you'd be safe to continue to use them if you understand them better.

Delegate:

$(selector).delegate(subselector, events, data, handler);
$(selector).on(events, subselector, data, handler);

Source:

delegate: function( selector, types, data, fn ) {
  return this.on( types, selector, data, fn );
}

tl;dr

If you want backwards compatibility, just keep using .delegate()docs, if your code relies on newer jQuery features, feel free to use on.

Community
  • 1
  • 1
zzzzBov
  • 174,988
  • 54
  • 320
  • 367
1

Consider using find() instead of event delegates. Look at this performance test: http://jsperf.com/jquery-event-delegation/85

Instead of

$("#mydomid").on("click", ".somechildclass", delegate);

use

$("#mydomid").find(".somechildclass").on("click", delegate);
Pål Thingbø
  • 1,211
  • 1
  • 17
  • 17
  • 13
    Sure, this works as long as your content isn't dynamically loaded. The best part about [.on() delegated events](http://api.jquery.com/on/#direct-and-delegated-events) is that they work on items that are added to the DOM **after** the event handler is bound. – Dave Nov 06 '14 at 18:48
  • 1
    Actually, @pål-thingbø, I suspect you were misreading the results. Since the results are displayed in "operations per second (higher is better)", `.on()` and `.delegate()` are much faster than the test case that uses `find()`. – Jeromy French Jan 29 '15 at 18:12
  • Among the "popular" browsers, `delegate()` somehow holds a slight edge over `on()`. This is really *really* odd, considering that `delegate()` is just a wrapper for `on()` in the latest 1.x jQuery (see https://github.com/jquery/jquery/blob/10399ddcf8a239acc27bdec9231b996b178224d3/src/event/alias.js#L31) – Jeromy French Jan 29 '15 at 18:22
  • So you're basically telling the guy who asked the question about event delegates to just nevermind that and use something totally different. Right. – Paul Ghiran Jun 22 '17 at 16:59
1

From the API:

"As of jQuery 1.7, .delegate() has been superseded by the .on() method."

"As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers."

Viruzzo
  • 3,025
  • 13
  • 13
  • 4
    Supersceded, but not deprecated. There are multiple sites advising use of delegate rather than on, mostly to do with the difficulty of spotting bugs and controlling unintended consequences when using parameter number and order to specify which of 3 methods (which are totally different under the hood) you want. I am sticking with delegate, and if it is ever deprecated I will roll-out my own wrapper, just to ensure that my team and I clearly see which method is actually being called. – DaveWalley Aug 22 '14 at 16:44
0

if you go through the jQuery Api you will find that both the same. Read More

For example, the following .delegate() code:

$("table").delegate("td", "click", function() {
$(this).toggleClass("chosen"); });

is equivalent to the following code written using .on():

$("table").on("click", "td", function() {
$(this).toggleClass("chosen"); });

Techie
  • 44,706
  • 42
  • 157
  • 243
0

.delegate() is equivalent to .on(): https://github.com/jquery/jquery/blob/bd9a138/src/event/alias.js#L31-33

.on() is preferred because it is shorter and it has a better parameters order.

Jakub Vrána
  • 614
  • 4
  • 14