Back to Home

Bubbling and capturing

Let’s start with an example. This handler is assigned to

, but also runs if you click any nested tag like or : Isn’t it a bit strange? Why does the handler on
run if the actual click was on ?

Bubbling

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: A click on the inner

first runs onclick: 1. On that

. 2. Then on the outer

. 3. Then on the outer
. 4. And so on upwards till the document object. So if we click on

, 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.

event.target

A handler on a parent element can always get the details about where it actually happened. The most deeply nested element that caused the event is called a target element, accessible as event.target. Note the differences from this (=event.currentTarget): - event.target – is the “target” element that initiated the event, it doesn’t change through the bubbling process. - this – is the “current” element, the one that has a currently running handler on it. For instance, if we have a single handler form.onclick, then it can “catch” all clicks inside the form. No matter where the click happened, it bubbles up to and runs the handler. In form.onclick handler: - this (=event.currentTarget) is the element, because the handler runs on it. - event.target is the actual element inside the form that was clicked. Check it out: [codetabs height=220 src=“bubble-target”] It’s possible that event.target could equal this – it happens when the click is made directly on the element.

Stopping bubbling

A bubbling event goes from the target element straight up. Normally it goes upwards till , 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

<div onclick="alert('The handler!')">
  <em>If you click on <code>EM</code>, the handler on <code>DIV</code> runs.</em>
</div>
Example:

Follow the lesson from Microsoft Web-Dev-For-Beginners course

Tags: web,development

© US Tutorials. All rights reserved.