jQuery: difference between .click() AND .on(“click”)

At the end of the day, every event is bound to some element in the DOM. In the case of .bind, you’re binding directly to the element (or elements) in your jQuery object. If, for example, your jQuery object contained 100 elements, you’d be binding 100 event listeners.

In the case of .live, .delegate, and .on, a single event listener is bound, generally on one of the topmost nodes in the DOM tree: document, document.documentElement (the <html> element), or document.body. Because DOM events bubble up through the tree, an event handler attached to the body element can actually receive click events originating from any element on the page. So, rather than binding 100 events you could bind just one.

For a small number of elements (fewer than five, say), binding the event handlers directly is likely to be faster (although performance is unlikely to be an issue). For a larger number of elements, always use .on.

The other advantage of .on is that if you add elements to the DOM you don’t need to worry about binding event handlers to these new elements. Take, for example, an HTML list:

<ul id="todo">
  <li>buy milk</li>
  <li>arrange haircut</li>
  <li>pay credit card bill</li>
</ul>

Next, some jQuery:

// Remove the todo item when clicked.
$('#todo').children().click(function () {
  $(this).remove()
})

Now, what if we add a todo?

$('#todo').append('<li>answer all the questions on SO</li>')

Clicking this todo item will not remove it from the list, since it doesn’t have any event handlers bound. If instead we’d used .on, the new item would work without any extra effort on our part. Here’s how the .on version would look:

$('#todo').on('click', 'li', function (event) {
  $(event.target).remove()
})

Leave a Comment