Last active
July 20, 2021 11:09
-
-
Save christianscott/64de318cea2e57ab65385d59a394d4da to your computer and use it in GitHub Desktop.
Preventing event bubbling in JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var el = document.createElement("div"); | |
document.body.innerHTML = ""; | |
document.body.appendChild(el); | |
document.body.addEventListener("foobar", announce); | |
el.addEventListener("foobar", preventBubble(announce)); | |
var event = new CustomEvent("foobar", { bubbles: true, detail: "Hello" }); | |
el.dispatchEvent(event); // "ANNOUNCING: Hello" | |
function announce(ev) { | |
console.log("ANNOUNCING: " + ev.detail); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function preventBubble(arg) { | |
if (arg instanceof Event) { | |
return _handleEvent(arg); | |
} | |
if (typeof arg === "function") { | |
return _handleFunction(arg); | |
} | |
throw new TypeError("Argument must be an Event or a callback"); | |
} | |
function _handleEvent(ev) { | |
if (ev.stopPropogation) { | |
ev.stopPropogation(); | |
} else { | |
ev.cancelBubble = true; | |
} | |
return ev; | |
} | |
function _handleFunction(callback) { | |
return function(ev) { | |
_handleEvent(ev); | |
return callback(ev); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment