<h3>Practice Set, Week 9, Event Handling and Bubbling</h3>
<p>This page contains two buttons, each with an event handler that causes the button, when clicked to echo its text to the page.</p>
<p>Your task is to rewrite the event handling code so that there is only one event handling function. That function should be called when a user clicks on <i>either</i> button. The output should remain identical. </p>
<p>You'll want to consider attaching a single event handler to a node further up the DOM tree, and checking there for which element was actually clicked (using a conditional). </p>
<p>Hint: this is exactly the process that's demonstrated in the video in Week 9 Lesson 2</p>
<div id="container">
<h4 id="output"></h4>
<body>
<button id="happyBtn" onclick="event.stopPropagation()">Coding can be fun!</button>
<button id="gloomyBtn" onclick="event.stopPropagation()">Coding can be maddening!</button>
</body>
</div>
var happy = document.getElementById("happyBtn");
happy.addEventListener("click", function(evt){
logMessage(evt.currentTarget.innerHTML);
});
var gloomy = document.getElementById("gloomyBtn");
gloomy.addEventListener("click", function(evt){
logMessage(evt.currentTarget.innerHTML);
evt.stopPropogation(); // still bubbling after entering the code
});
// Utility function for logging convenience
// Logs msg to the element with given id
// If id is undefined, logs to #output
function logMessage(msg, id){
if (!id){
id="output";
}
document.getElementById(id).innerHTML += msg + "<br>";
evt.stopPropogation();
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.