×


Event propagation in javascript – Capturing and Bubbling

Event propagation is the propagation of an event through the elements in the HTML DOM.

When an event happens

phase1 – Event Capturing is done until the target is reached

phase2 –  Bubbling is done executing handlers on the way

Event bubbling and capturing are the two ways of event propagation in processing an event by the HTML DOM API.Event bubbling means that when an event happens, it propagates all the way up the parent to the ancestor elements.

Bubbling

When an event happens on an element,say click, it first runs the handlers on it, then on its parent, then all the way up.See the below example
-The button inside the wh4 div was clicked. Onclick handler is on the ancestor wh4 is run.

 

Not every event get bubbled.Here is a list of  the most common event handlers.

onAbort
onBlur
onChange
onClick
onDblClick
onDragDrop
onError
onFocus
onKeyDown
onKeyPress
onKeyUp
onLoad
onMouseDown
onMouseMove
onMouseOut
onMouseOver
onMouseUp
onMove
onReset
onResize
onSelect
onSubmit
onUnload

Not every event bubbles.

If x is true then the event bubbles.You can check this creating the event

By default all the Browsers support event bubbling.

Event Capturing

When an event happens capturing occurs in a way  that event propagates all the ways from the window to the target element and then it bubbles up.In the above example,event propagates in the following way from the window to the  element(Capturing)

WINDOW

DOCUMENT

DIV – Class wh1

DIV – Class wh2

DIV – Class wh3

DIV – Class wh4

BUTTON -This is the target

On reaching the target , bubbling happens calling the handlers on the way.

Doing something on the event capturing phase is never used in real code.To do this you can use the following code

Stopping Propagation

Some times you may need to stop propagation.For stopping propagation,the following code is used.

 

event.stopImmediatePropagation()

If an element has multiple event handlers on a single event, then even if one of them stops the bubbling, the other ones still execute.

Its not good to stop propagation with out need.Use cases for stopping propagation are rare.

 

SOME INTERESTING SOURCES

https://developer.mozilla.org/en-US/docs/Web/API/Event/bubbles

https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Event_handlers

 

 

No Comments

Leave a Reply

Your email address will not be published. Required fields are marked *