Skip to content

Instantly share code, notes, and snippets.

@sudocurse
Created March 4, 2019 21:00
Show Gist options
  • Save sudocurse/7f417dc41e0b665f7f4f37465d940436 to your computer and use it in GitHub Desktop.
Save sudocurse/7f417dc41e0b665f7f4f37465d940436 to your computer and use it in GitHub Desktop.
javascript event order for an onclick
<html>
<body>
<div id="elem1">
<div id="elem2">
Hi
</div>
</div>
<script>
count = 0;
ha = function(obj){
var handling = "";
count += 1;
// event property obj.bubbles will check if the event type is one that bubbles or not.
// var canThisBubble = obj.bubbles;
switch(obj.eventPhase) {
case 1: handling = "bubbling"; break;
case 2: handling = "target"; break;
case 3: handling = "capturing"; break;
}
console.log(`The event received by ${obj.target.id} has been passed to ${this.id}. The handler was run the ${count}th time. This handler is in the ${handling} phase.`);
}
elem1 = document.getElementById('elem1');
elem2 = document.getElementById('elem2');
elem1.addEventListener('click', ha, true); // bubbling
elem2.addEventListener('click', ha, true); // target element
elem2.addEventListener('click', ha, false); // target element
elem1.addEventListener('click', ha, false); // capture
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment