What is the difference between:

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

and

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

What is the fundamental difference and does it affect the speed of work?

  • The principal difference is: in the second case - a click will hang only on those elements that are already in the house - Grundy
  • And through the document, the element to which the click is attached will be searched each time from the root of the document? - pawheel
  • @pawheel, in the first case, if you dynamically add html with these links, they will also be processed, but in the second they will not, only I usually use not $(document) , but $('body') - MasterAlex
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

1 answer 1

$(document).on('click', '.selector', function(){}) or $('.parentSelector').on('click', '.childSelector', function(){}) - delegation events

Should use:

  1. If we have a large number of the same type of elements on which you need to listen to the same events.
    For example, anchor navigation with a large number of points, for implementing a smooth scroll or filter in a store, for sending ajax requests with each click on a filter item, etc. - weight options.
  2. If the elements on which you want to listen to events can be created dynamically, while the site is running.

The whole point is that one event is hung on the parent selector (or higher selector), which responds to pop-up events from the child elements.
In terms of performance, this method is better when the conditions described above are met.
But I do not recommend hanging on the document or on the body unless absolutely necessary, because it negatively affects the performance . Try to use a more direct parent selector.

$('.selector').on('click', function(){}) should be used in all other cases, since best performance is achieved.