1

Imagine the following use case:

A page contains a multitude of buttons, each of them triggers different functions. The examples what I saw added event listeners to every button.

However what will happen if I add an event listener to the whole document, then extract the given element from the point, so I know what was clicked, and call a function accordingly.

In that case there is only one event listener, and not as many as number of the buttons.

Will this method give me performance gain?

atevm
  • 571
  • 8
  • 22
  • 2
    This is essentially how jQuery live events work, except the browser provides the original element. It is not determined from a point by jQuery but rather by the browser. – Dark Falcon Feb 26 '16 at 17:09
  • 2
    [AKA "event delegation"](http://stackoverflow.com/questions/1687296/what-is-dom-event-delegation). And yes, one event listener is better than 100 performance-wise. – Andy Feb 26 '16 at 17:09
  • @DarkFalcon Thanks it was very useful. Shall I update/edit my question to meet some criteria. However I do not know what I did wrong, or should I delete it, if it so misleading? – atevm Feb 26 '16 at 17:26
  • 2
    @Andy as this is the top result for the query on google, perhaps you should make your comment an official answer? OP, Nice one for figuring this out without knowing about it beforehand. – Polyducks Feb 26 '16 at 17:33
  • 1
    Polyducks is right. @Andy or Dark Falcon please answer it, only a experienced JavaScript programmer will search for event delegation on the web. An other newbie like me maybe ask the same question. – atevm Feb 26 '16 at 17:38
  • 2
    In agreement with @Polyducks too: kudos for figuring that out without knowing what the technical term was. Very well described. – Andy Feb 26 '16 at 17:45

1 Answers1

2

What you're describing is a feature of the way JavaScript events interact with the DOM known as event delegation.

Basically by adding a listener to a parent element it can catch and process events from its child elements that "bubble up" when they've been activated.

This method is less resource intensive than the alternative of adding the event listeners to every child element.

Community
  • 1
  • 1
Andy
  • 39,764
  • 8
  • 53
  • 80