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


what significant difference between following two?

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

i have noticed first 1 more of dynamic thing. if have static selectors, should use? performance? prefered?

and that: use delegation? side effects?

answer here explains use of both: direct vs. delegated - jquery .on(). wanted see performance , best practices do.

this one

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

attaches event body itself, means elements added dom after has loaded inherit event (providing they're #selector of course).

whereas one:

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

is still delegated event, won't applied elements dynamically added dom.

it better delegate events because of improved performance (especially when have plenty of elements subscribed same event).

however, in scenario event id there's going 1 match (if have duplicate elements same id, it'll still match 1) there's no real benefit in delegating event (unless you're adding said element dynamically of course).


Comments