X Pahadi
X Pahadi

Reputation: 7443

jQuery `on` and related selectors [Body vs Exact Element Selection]

What is the significant difference between the following two?

$('body').on('click','#selector', function{...})
$('#selector').on('click', function{...})

I have noticed that the first one more of dynamic thing. If I have static selectors, which should I use? What is the performance? What is prefered?

And Is it that: Always use delegation? What are the side effects?

Answer here explains the use of both: Direct vs. Delegated - jQuery .on(). I wanted to see the performance and best practices to do.

Upvotes: 4

Views: 84

Answers (3)

Pudd
Pudd

Reputation: 447

The main difference is delegation.

Your first example hooks the click event to the body and checks anything that propagates from child elements, checking it for the selector #selector. This is useful for picking up events on elements not currently in the DOM or that get dynamically created and destroyed.

Your second will hook to the #selector itself. This will break if #selector is removed from the DOM, but it doesn't have to listen to every child element and check it to see if it triggers an event.

Upvotes: 0

Radonirina Maminiaina
Radonirina Maminiaina

Reputation: 7004

An event-delegation approach attaches an event handler to only one element, the tbody, and the event only needs to bubble up one level (from the clicked tr to tbody):

Here's an example:

$( "#dataTable tbody" ).on( "click", "tr", function() {
  console.log( $( this ).text() );
});

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

Upvotes: 0

Mathew Thompson
Mathew Thompson

Reputation: 56429

This one

$('body').on('click','#selector', function{...})

Attaches the event to the body itself, which means that any elements that were added to the DOM after it has loaded will also inherit this event (providing they're #selector of course).

Whereas this one:

$('#selector').on('click', function{...})

Is still a delegated event, but won't be applied for elements dynamically added to the DOM.

It is better to delegate your events because of the improved performance (especially when you have plenty of elements subscribed to the same event).

However, in your scenario your event is only an ID so there's only going to be 1 match (if you have duplicate elements with the same ID, it'll still only match 1) so there's no real benefit in delegating the event (unless you're adding said element dynamically of course).

Upvotes: 5

Related Questions