Practice Set, Week 9, Event Handling and Bubbling

by subsari

HTML

<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>
    <button id="happyBtn">Coding can be fun!</button>
    <button id="gloomyBtn">Coding can be maddening!</button>
</div>

CSS

.button {
    text-indent:0;
    border:1px solid #eda933;
    display:inline-block;
    color:#ffffff;
    font-family:Arial;
    font-size:15px;
    font-weight:bold;
    font-style:normal;
    height:65px;
    line-height:65px;
    padding: .5 em;
    text-decoration:none;
    text-align:center;
    text-shadow:1px 1px 0px #cd8a15;
    background-color:#f6b33d;
}

JavaScript

var happy = document.getElementById("happyBtn");
// removed code - refactored to single event handler
//happy.addEventListener("click", function(evt){
//    logMessage(evt.currentTarget.innerHTML);
//});
var gloomy = document.getElementById("gloomyBtn");
// removed code - refactored to single event handler
//gloomy.addEventListener("click", function(evt){
//    logMessage(evt.currentTarget.innerHTML);
//});

var container = document.querySelector("#container");
container.addEventListener('click', containerClickHandler);

function containerClickHandler(e){
	// stop propagation for additional performance
	// as suggested by kirupa in assignment video link
	e.stopPropagation(); 
	
	switch(e.target.id){
		case "happyBtn":
		case "gloomyBtn":
			logMessage(e.target.innerHTML);
			break;
	}
}

// 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>";
}