简体   繁体   中英

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)?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM