HTML and CSS Reference
In-Depth Information
The last parameter of the addEventListener method accepts an optional Boolean parameter.
This parameter allows you to specify the cascading or bubbling effect of the event—that is to
say, in which order the event processing occurs. The click event for each div has an event listener
assigned. In the preceding example, the three div elements are nested. A user who clicks the
inside or middle div also clicks the parent div because the div elements share the same physical
space on the screen. When the blue inside box is clicked, the following output is displayed:
1. inner Div Clicked
2. middle Div Clicked
3. outer Div Clicked
One click event triggered all three events to fire. This concept is called event bubbling.
Clicking directly on the middle green div produces the following output:
1. middle Div Clicked
2. outer Div Clicked
Finally, clicking the red outer div produces this output:
1. outer Div Clicked
The event has bubbled up to the top. If you prefer to have the events handled in the
opposite order—that is, to have them cascade down—the last parameter specified by the
addEventListener method is specified as true. With this change made, as follows,
document.getElementById("outer").addEventListener("click", outerDivClick, true);
document.getElementById("middle").addEventListener("click", middleDivClick, true);
document.getElementById("inner").addEventListener("click", innerDivClick, true);
the screen output is now as follows:
1. outer Div Clicked
2. middle Div Clicked
3. inner Div Clicked
The order of the event processing has reversed to be cascading instead of bubbling.
The cascading or bubbling effect of the events is convenient when you want it. However, the
design of the webpage could involve nested elements, but each element's click event should
run only if the element is directly clicked. In this case, you can use a property of the event object
called cancelBubble . If this property is set to true, the event bubbling or cascading stops with
the event listener that sets it. This stops only the bubbling or cascading behavior. The code to
cancel the bubbling of the event is added to the inner div element's event listener:
function innerDivClick() {
appendText("inner Div Clicked");
window.event.cancelBubble = true;
}
Now, when the inner div is clicked, the output is as follow:
1. inner Div Clicked
The bubbling of the event up to the middle div and outer div has been prevented.
 
Search WWH ::




Custom Search