Skip to content Skip to sidebar Skip to footer

Why It Is Bad Practice To Register Events To Document In Jquery?

Whenever I read about event registration in jquery they all say that we should try to add event handlers to the nearest parent, and avoid adding event listeners to the document, be

Solution 1:

Event delegation basically uses 2 different process,

  1. The event bubbling, For example, when you click over an element that event will be bubbled up to the document to fire the relevant event.
  2. The match, after reaching the document(during event bubbling) the fellow who caused the event bubbling will be verified with the selectors attached with document. If it matches then the relevant event will be fired.

So you are advocating about the match by stating a generic selector. To be frank, matching 2 or 3 elements will take less time than traversing up to the document during event bubbling. At that case if you use a static closest parent instead of document, the traversing time will be reduced and that will hike the performance.

Though match takes less time, when it comes with 15+ elements for matching, that will also affect the performance even when you use closest parent instead of document.

So the summary is, we have to use event delegation sparingly with common sense by knowing the above two different process takes place under the hood.

Post a Comment for "Why It Is Bad Practice To Register Events To Document In Jquery?"