Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop propagation for all events

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?

like image 487
alh Avatar asked Feb 12 '14 09:02

alh


3 Answers

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

like image 139
Alex Avatar answered Nov 16 '22 09:11

Alex


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/

like image 21
Prashobh Avatar answered Nov 16 '22 08:11

Prashobh


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

like image 9
FloG Avatar answered Nov 16 '22 09:11

FloG