Event Propagation, Event delegation, bubbling and capturing, what is it?

Tram Ho

Don’t go round and round and go straight to the point

Concept

  • Propagation (propagation)
  • Bubbling (bubbling): refers to going from below the roots to the base of the tree
  • Capturing: the intention to go from the base of the tree
  • Target : where the DOM element registers an event (href, onclick, scroll, …)

Look at this picture to understand
alt

Event capturing

When we proceed to click a card it will capture from the top level card down

  • Capturing : window -> document -> html -> body -> div#wrap -> p.hint -> a
  • Target : here is href =’#’
  • Bubbling : it goes against capturing

Flow behaves like this after an event – most cases: Capturing > target > bubbling

Event Delegation

Delegation means that when we create an event for the parent class, the inner child classes also receive that event.

We proceed to attach events to taskList

If you’re lazy, go here and copy and paste the code quickly, this one has a prompt to type happily, type clg to console.log(), type div out full syntax, but if you type a lot it tells thêm tiền đi em iu : https:// playcode.io/new

When we click any li , it console.log the corresponding class. Authorization – delegation (from parent to child) here means that we only need to attach 1 event to the parent tag. No matter how many li tags inside the event is received.

Event Bubbling

Example 1: There is code as follows

When we proceed to click the p tag it will alert all p > div > form

When we proceed to click the div tag it will alert all div > form . Then it’s easy to understand.

Clicking on the child means you also click on the parent element!!!

Example 2:

When we click on div3 it logs out 3 -> 2 -> 1 just like the guy above.

event.stopPropagation – stop bubbling

Now click on any div it will only log the class of that div !!!

summary

It’s almost all about Propagation in js. Have a nice day bro.

Share the news now

Source : Viblo