1

How to use events in jQuery?

I have 2 projects and in both projects I use different way to set events with jQuery. In first project I use like this:

$("#someID").click(SomeFunction);

In second project I use like this:

$(document).on("click", "#someID", SomeFunction);

If I try to use first way in second project it will not work. I like first way more. What is different?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Raskolnikov
  • 3,791
  • 9
  • 43
  • 88

7 Answers7

12

The first example is a normal click event binding. In that case element should be present on the dom at the time of binding. This will not work for dynamically generated html.

Second one is event delegation method. In this case elements can be dynamic. That is you can bind the event for future elements.

Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53
8

The second way uses a lazy event handler. This means that if you manipulate the DOM after you have initialized these events, only the second method will work.

This is because the second event handler attaches to the document and not the #someID element directly. Whenever the user clicks in the document, jQuery will determine if the clicked element matches the #someID selector, and only then will it fire the configured event.

This allows you to add the #someID element at a later point, even after the events have been configured.

The official name for this is event delegation, and you can find more info and examples here.

Edit: note that there is a performance penalty when using the second method. This is because jQuery has to search through your entire document for matching elements on every click. While #someID can probably be matched in a very fast, performant manner, you should at least be aware of this mechanism.

If you still want the advantage of having lazy events but want to minimize the performance overhead, I would advise you to narrow the scope in which jQuery has to search. For example, if the #someID element will always appear in the #someContainer element, you should configure your event like this:

$("#someContainer").on("click", "#someID", SomeFunction);

Another thing to note is that this method can also have performance gains. I am speaking from personal experience and have no benchmarks to prove this, but I noticed a smoother experience when using this method on a large collection of objects, for example a ul tag with lots of li tags, where each li tag needed an event listener. In this scenario, it was better to attach one event listener to the ul tag rather than attach n events to n li tags.

Moeri
  • 9,104
  • 5
  • 43
  • 56
  • FYI, it's called **event delegation**, not "lazy event handling". – Felix Kling Sep 24 '14 at 20:20
  • OK, I've added it to my post, I used the word "lazy" because I value the importance of simplicity over semantics. A rose by any other name... :) – Moeri Sep 25 '14 at 06:42
1

The first method uses a function handle to bind as a callback. It can only be used if the element with someId already exists on the page.

The second approach delegates the click event to any element on the page matching someId at any time, and uses a function handle bound as a callback.

The difference is the event delegation.

Travis J
  • 81,153
  • 41
  • 202
  • 273
1

Below code will bind click event to element with id="someID", but it will fail to bind click event if this element generated dynamically.

$("#someID").click(SomeFunction);

To bind event to dynamically generated element we use code as shown below i.e. using .on()

$(document).on("click", "#someID", SomeFunction);
Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57
0

Is better to use the second way:

$([selector]).on('[EVENT]',function(e){
    ...
});

You may also see arount this way:

$([selector]).bind('[EVENT]',function(e){
    ...
});

But jQuery recommends using .on instead of bind nor click, actually bind is deprected, so always use .on which is better.

Manjar
  • 3,159
  • 32
  • 44
0

This are just different ways of binding events. You also need to consider that .on was is not supported in older version of jquery.

Mahesh Thumar
  • 4,257
  • 5
  • 22
  • 30
0

Your both methods will work for static website.
But if you have something like this: $('div').append('<div class="new"></div>'), than $('.new').click() will not work, because when you bind event to .new, there is no such element yet in DOM and no event is attached to element.
To bind events to dynamic elements, use $(document).on('event', 'selector', function). And it must be applied on static element (for now it's document element).

Justinas
  • 41,402
  • 5
  • 66
  • 96