1

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

1
  • 1
    There is no one event for just all the events. Commented Oct 9, 2014 at 19:21

1 Answer 1

3

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.