Question

Is there a JQuery function (or plugin) to handle all mouse events at once?

For example, I can use $("*").click() to handle all click events in a page but I'm wondering if there's a function like:

$("*").mouseEvent("event type", function(){
    // handle all events based on their event type in one listener
});
Was it helpful?

Solution

You can use delegated event handling to listen for all mouse events via event propagation. You can pass multiple event names to the same event handler. You can then look at event parameters when the event fires to see which type of event occurred on which DOM object.

$(document).on("mouseup mousedown click mousemove", function(e) {
    // e.type is the type of event
    // e.target is the element the event originally occured in
});

This has the advantage that it works for all elements in the page, even dynamic objects added AFTER you install the event handler.

The only disadvantage of doing it this way is that you usually cannot prevent the default behavior of the event because it may have already been processed by an event handler attached directly to the object (except you can prevent links from firing with e.preventDefault() because they apparently don't fire until after event propagation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top