Everything is created from some event even our Universe and the little Browser Popup.
What is an event ?
It is an occurrence of different activities, right?
Events in Browser
There are different type of action that are performed on dom are called events
Some events as follows
- click
- keyup/keydown
- Mouseover/out
The function which executes when a certain event occur is called Event Handler
and this is how we write event handlers in a different ways.
1. <button id="btn" onClick="alert('clicked')">Click</button>
2. <button id="btn">Click</button>
<script>
btn.onclick = function () {
console.log("clicked");
};
</script>
I hope it was a good review of the basics.
But do you know how dom reacts when events happen on an element?
<section onClick="alert('i am section')">
<div onClick="alert('i am div')">
<p onClick="alert('i am p')">click me</p>
</div>
</section>
Now if the user click on the p element all three alert box will pop up.
Bit strange right?
This is called a Bubbling effect.
Whenever an event happens it runs an event handler on that element, then on the parent element and then all the way to root elements.
Detailed Points of what will happen if the user click on the p
element
A
p
element event handler will run which isonclick
and then the Browser will generate an alert box displaying i am p.If the parent element contains the same event handler then the parent element handler will also execute.
In this case div contains the same event handler
onclick
so that handler will be called too.This process continues to the root element.
Thus, the section element event handler also generate an alert box.
This Bubble effect will end on the
document
object.
This bubbling effect works like a bubble that is created when a stone or a raindrop fall on lakes.
Every event show bubble effect except some few instances
To check if the event show bubble effect
event.bubbles
will return a boolean value
Stop a Bubbling effect
There are two functions which can stop a bubble effect
event.stopPropagation()
- stop the handler of current element
and restrict the bubble effect.
<section onClick="alert('section')">
<div onClick="alert('div')">
<p onClick="event.stopPropagation()">click me</p>
</div>
</section>
<!-- no alert box will generate -->
event.stopImmediatePropagation()
- If the current element has
more handler on same event.
<section onClick="alert('section')">
<div onClick="alert('div')">
<p onClick="event.stopImmediatePropagation()"
onClick="alert('second hanlder')">click me</p>
</div>
</section>
<!-- no alert box will generate -->
Although Developers avoid the restriction on the bubble effect because it can lead to some large pitfalls.
Think and comment down some examples of pitfalls.
Thank you for your read!!
If you find this helpful share this with your fellow Devs.
Top comments (0)