mrturtle
mrturtle

Reputation: 297

JQuery event handler with or without on?

If I have a dropdown in my html document looking like this:

<select id="myDropdown">
  <option value="apple">Apple</option>
  <option value="orange">Orange</option>
  <option value="banana">Banana</option>
</select>

and I want to hook up on the change event with JQuery, then both of these approaches seem to work with JQuery:

$("#myDropdown").change(function () {
   // Do something
});

and

$('#myDropdown').on('change', function () {
   // Do something
});

What is the difference between these two, and is one of them to prefer?

Upvotes: 2

Views: 95

Answers (2)

Ronen Cypis
Ronen Cypis

Reputation: 21470

$.on(...), is much more powerful approach since it allows you to attach only one event listener on a container, and provide it with matching selectors, instead of attaching tons of event listeners... For example, this code:

$('#container .item').click(function(){ ... });

VS

$('#container').on('click', '.item', function(){ ... });

The .click() approach attaches event listener to every .item element- possibly A LOT of them on page...

The .on('click'...) approach only attach one event listener to the #container element, and on every click it checks if the element that triggered the event is an .item element, and if so- executes the callback function.

The .on(...) function also "catch" .item elements that are not on the page when this piece of js runs, not like the .click() method that only binding currently existing .item elements, and you would need to bind it manually if you later inject newly created .item elements to the page.

Upvotes: 1

Jai
Jai

Reputation: 74738

See, both are called event binding, there is no difference but .on() has some advantages over direct event binding (don't have right word for it).

The advantage with .on() method is event delegation, which is useful when you have a dynamically created element in the page. It has a bit specific syntax but uses .on() method:

$(staticParent).on(event, selector, callback);

There is another advantage of .on() method is, if you have bound any event on a selector then that event can be called off with .off() method.

Also want to mention that .on()/.off() has replaced the .bind()/.unbind() methods and about event delegation it has replaced .live()/.die().

Upvotes: 2

Related Questions