10.3 Events Bubbling
Now that we know how to handle events, let’s explore another important concept in event handling – the concept of event bubbling.
To understand event bubbling, add the following code to EventsPractice.html (after the <body> opening tag).
<div id = "parent">Parent Element <p id = "child">Child Element</p> </div>
This code adds two elements – <div> and <p> – to the HTML page. The <p> element is enclosed within the <div>…</div> tags. Hence, it is a child element of the <div> element.
Now, add the following code to chap10.js:
function parentEventHandler(){ alert("Parent Event Handler"); } function childEventHandler(){ alert("Child Event Handler"); } document.getElementById("parent").addEventListener('click', parentEventHandler); document.getElementById("child").addEventListener('click', childEventHandler);
Save chap10.js and refresh EventsPractice.html.
Click on the line that says "Parent Element".
What happens? You see a pop-up window that says "Parent Event Handler", right? This is due to the parentEventHandler() function that we added to the parent element's event listener.
Next, click on the line that says "Child Element". You’ll see a pop-up window that says "Child Event Handler". No surprises here.
Now, click OK to dismiss this window. What happens next?
You see another pop-up window that says "Parent Event Handler", right?
This may come as a surprise to you. The reason for the second pop-up window is event bubbling.
Suppose we have two HTML elements such that one is a child element of the other. The event handlers for the parent element apply to all the child elements as well. Hence in our example, when we click on the child element, the event handlers for both the child and parent elements are triggered.
This feature is very useful if we want to apply an event handler to all the child elements of a particular element. Instead of adding it to each child element separately, we can add it to the parent element. This helps to save a lot of effort when there are a lot of child elements.
On the other hand, if we do not want event bubbling to occur, we can use the built-in stopPropagation() method. To do that, we need to pass in an Event object to our function and use it to call the stopPropagation() method. Let’s try that now. Change the childElementHandler() function to
function childEventHandler(e){ alert("Child Event Handler"); e.stopPropagation(); }
and run the program again. You’ll only see one pop-up window this time.