The bubbling principle is simple.
When an event happens on an element, it first runs the handlers on it, then on its parent, then all the way up on other ancestors.
Let’s say we have 3 nested elements FORM > DIV > P with a handler on each of them:
Click here for demo. https://www.w3schools.com/
A click on the inner <p> first runs onclick:
On that <p>.
Then on the outer <div>.
Then on the outer <form>.
And so on upwards till the document object.
So if we click on <p>, then we’ll see 3 alerts: p → div → form.
The process is called “bubbling”, because events “bubble” from the inner element up through parents like a bubble in the water.
Stopping bubbling
A bubbling event goes from the target element straight up. Normally it goes upwards till <html>, and then to document object, and some events even reach window, calling all handlers on the path.
But any handler may decide that the event has been fully processed and stop the bubbling.
The method for it is event.stopPropagation().
For instance, here body.onclick doesn’t work if you click on <button>:
Reference : https://javascript.info/
0 comments:
Post a Comment