Binding multiple events to a listener (without JQuery)? Binding multiple events to a listener (without JQuery)? jquery jquery

Binding multiple events to a listener (without JQuery)?


Some compact syntax that achieves the desired result, POJS:

   "mousemove touchmove".split(" ").forEach(function(e){      window.addEventListener(e,mouseMoveHandler,false);    });


In POJS, you add one listener at a time. It is not common to add the same listener for two different events on the same element. You could write your own small function to do the job, e.g.:

/* Add one or more listeners to an element** @param {DOMElement} element - DOM element to add listeners to** @param {string} eventNames - space separated list of event names, e.g. 'click change'** @param {Function} listener - function to attach for each event as a listener*/function addListenerMulti(element, eventNames, listener) {  var events = eventNames.split(' ');  for (var i=0, iLen=events.length; i<iLen; i++) {    element.addEventListener(events[i], listener, false);  }}addListenerMulti(window, 'mousemove touchmove', function(){…});

Hopefully it shows the concept.

Edit 2016-02-25

Dalgard's comment caused me to revisit this. I guess adding the same listener for multiple events on the one element is more common now to cover the various interface types in use, and Isaac's answer offers a good use of built–in methods to reduce the code (though less code is, of itself, not necessarily a bonus). Extended with ECMAScript 2015 arrow functions gives:

function addListenerMulti(el, s, fn) {  s.split(' ').forEach(e => el.addEventListener(e, fn, false));}

A similar strategy could add the same listener to multiple elements, but the need to do that might be an indicator for event delegation.


Cleaning up Isaac's answer:

['mousemove', 'touchmove'].forEach(function(e) {  window.addEventListener(e, mouseMoveHandler);});

EDIT

ES6 helper function:

function addMultipleEventListener(element, events, handler) {  events.forEach(e => element.addEventListener(e, handler))}