Ygandelsman Ygandelsman - 1 month ago 14
Javascript Question

Detect any mouse event in the page using JavaScript

I want to write in

javascript
a generic
eventListener
for any possible mouse event.

I am trying to write an
eventListener
that handles any mouse moves inside the webpage, presses of any kind, scrolling and everything that can be done using the mouse.

I didn't find a good way to do it, also because I need it to be done using pure
javascript
without
jquery
or any other libraries, just using simple DOM elements and function.

Can anyone show me how it is done by writing one good handler (and not a handler for each possible event)?

Answer

What you can do is add event listeners for all mouse events but use the same handler function. Something like this:

function bindEventsToSameHandler(element, events, handler) {
    for(var i = 0; i < events.length; i++) {
        element.addEventListener(events[i], handler);
    }
}

// ...

// usage
var element = document.getElementById('selector'); // select the element on which to handle mouse events
var events = ['click', 'mouseup', 'mousedown'];    // add mouse events you want to handle
bindEventsToSameHandler(element, events, function() {

    // your handler code goes here

});

Note: this would work for any event, not just the ones related to the mouse.

Here's an example:

function bindEventsToSameHandler(element, events, handler) {
    for(var i = 0; i < events.length; i++) {
        element.addEventListener(events[i], handler);
    }
}

// usage
element = document.getElementById('capture');
events = ['click', 'dblclick', 'mouseup', 'mousedown']; // add your events here
bindEventsToSameHandler(element, events, function(e) {
    console.debug('handled ' + e.type);
});
#capture {
    
    width: 100%;
    height: 100%;
    border: 1px solid black;
    padding: 100px;
}
<body>
    
    <p id='capture'>CAPTURE EVENTS BOX</p>
    
</body>