I am calling e.stopPropagation()
on almost every event that I have for my current application. Is there any way to just stop the propagation for every event without having to explicitly call the method at the start of every function body?
You could bind all events (remove the ones you don't need):
$('*').bind('blur change click dblclick error focus focusin focusout hover keydown keypress keyup load mousedown mouseenter mouseleave mousemove mouseout mouseover mouseup resize scroll select submit', function(event){
event.stopPropagation();
});
Take a look at possible events at jQuery Docs
No it cannot be declared Globally
The event.stopPropagation()
method stops the bubbling of an event to parent elements, preventing any parent event handlers from being executed.
For example, if there is a link with a click method attached inside of a DIV or FORM that also has a click method attached, it will prevent the DIV or FORM click method from firing.
http://api.jquery.com/event.stopPropagation/
To build on Alex's response, in vanilla JS and with a few more events (all the keyboard and click events I could find):
/**
* Disable all user events on the page
*
* @returns {function()} a function to cancel the disabling
*/
const disableAllUserEvents = () => {
const events = ["click", "contextmenu", "dblclick", "mousedown", "mouseenter", "mouseleave", "mousemove",
"mouseover", "mouseout", "mouseup", "keydown", "keypress", "keyup", "blur", "change", "focus", "focusin",
"focusout", "input", "invalid", "reset", "search", "select", "submit", "drag", "dragend", "dragenter",
"dragleave", "dragover", "dragstart", "drop", "copy", "cut", "paste", "mousewheel", "wheel", "touchcancel",
"touchend", "touchmove", "touchstart"];
const handler = event => {
event.stopPropagation();
event.preventDefault();
return false;
};
for (let i = 0, l = events.length; i < l; i++) {
document.addEventListener(events[i], handler, true);
}
return () => {
for (let i = 0, l = events.length; i < l; i++) {
document.removeEventListener(events[i], handler, true);
}
};
};
Edit: Just know that this isn't a secure solution, as those events can be retrieved and canceled: Use Chrome's webkit inspector to remove an event listener
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With