Skip to content

Instantly share code, notes, and snippets.

@m-arrieta-r
Last active July 19, 2016 16:57
Show Gist options
  • Save m-arrieta-r/fd673f27d379e0e95544c630ffee5477 to your computer and use it in GitHub Desktop.
Save m-arrieta-r/fd673f27d379e0e95544c630ffee5477 to your computer and use it in GitHub Desktop.
Playing around with js events
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Bubbling ex</title>
<style>
body {
height: 50vh;
}
.div1 {
width: 90%;
height: 90%;
background-color: red;
}
.div2 {
width: 90%;
height: 90%;
background-color: blue;
}
.div3 {
width: 90%;
height: 90%;
background-color: green;
}
</style>
</head>
<body>
<div class="div1">
<div class="div2">
<div class="div3">
</div>
</div>
</div>
<div id="resultBox">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
var div1 = document.querySelector('.div1');
var div2 = document.querySelector('.div2');
var div3 = document.querySelector('.div3');
var html = document.querySelector('html');
var body = document.querySelector('body');
var resultBox = document.querySelector('#resultBox');
function appendResult(thisElement, event) {
var tagName = whoAmI(thisElement);
var target = whoAmI(event.target);
var currentTarget = whoAmI(event.currentTarget);
resultBox.innerHTML += "I'm " + tagName + ", ";
resultBox.innerHTML += "Now the currentTarget is " + currentTarget + ", ";
resultBox.innerHTML += "Now the target is " + target + "<br></br>";
}
function whoAmI(element) {
var myName = element.tagName;
if(typeof myName === "undefined") {
myName = element.toString();
} else if(myName === "DIV") {
myName = element.classList.toString();
}
return myName;
}
window.addEventListener('click', function (e) {
appendResult(this, e);
});
document.addEventListener('click', function(e) {
appendResult(this, e);
});
html.addEventListener('click', function(e) {
appendResult(this, e);
});
body.addEventListener('click', function(e) {
appendResult(this, e);
});
div1.addEventListener('click', function(e) {
appendResult(this, e);
//e.stopPropagation();
//resultBox.innerHTML += "stopPropagation!!";
});
div2.addEventListener('click', function(e) {
appendResult(this, e);
});
div3.addEventListener('click', function(e) {
appendResult(this, e);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment