Skip to content

Instantly share code, notes, and snippets.

@christianscott
Last active July 20, 2021 11:09
Show Gist options
  • Save christianscott/64de318cea2e57ab65385d59a394d4da to your computer and use it in GitHub Desktop.
Save christianscott/64de318cea2e57ab65385d59a394d4da to your computer and use it in GitHub Desktop.
Preventing event bubbling in JS
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);
}
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