Event Delegation in JavaScript

Event Delegation in JavaScript

1.- Event

The events are actions that occur when we interact with a web, for example, when we click on a button, write in an input text. They are the way html and javascript interact. When an event is triggered, the browser notifies the application that something has happened and that it needs to be handled. Events are controlled by javascript functions, so when that event occurs, the browser alerts our function that is listening that it should be executed.

2.- How events work ?

  • The event travels down from window, document, root element and through the ancestors of the target element (capture phase)
  • The event occurs on the target (the target phase)
  • Finally, the event bubbles up through the target’s ancestors until the root element, document and window (the bubble phase).

3.-Event delegation

Event delegation consists of listening for events on the parent element to capture them when they occur in its children.

Making the event delegation work requires 3 steps:

  • Determine the parent of elements to watch for events
  • Attach the event listener to the parent element
  • Use event.target to select the target elements

4.-Example

4.1- Without event delegation

We add an event to each list item

On this case we would have:

  • One event for each item in the list. Let’s imagine we have 50 elements, we would have 50 <li> with 50 events.
  • In addition, if this table had pagination, every time we change pages, we would have to declare the events again, because when we change pages, we would lose them.

4.2- With event delegation

On this case we would have:

now we have a single event attached to the parent element, this allows us to propagate the event to its child elements

Every event listener you create uses memory in the browser. In terms of performance, it’s “cheaper” for the browser to track one event and fire it on every click that it is to manage multiple events.

As an added benefit, you can dynamically add elements to the DOM later and your event listener will catch them, too, since it checks for the selector when the event fires rather than ahead of time.

5.-Conclusion

In this article I’ve covered a technique called event delegation. The latter consists of adding an event listener to an ancestor of the element(s) on which the event of interest will be fired and takes advantage of the propagation of events in the DOM.

Event delegation allows a web developer to save memory when managing events and it’s especially convenient when working with web pages where elements are dynamically added and deleted.


avatar

Raul Hernandez

0
0

Laisser un commentaire