coiso coiso - 1 year ago 76
HTML Question

adding multiple event listeners to one element

So my dilemma is that I don't want to write the same code twice. Once for the click event and another for the

touchstart
event.

Here is the original code:

document.getElementById('first').addEventListener('touchstart', function(event) {
do_something();
});

document.getElementById('first').addEventListener('click', function(event) {
do_something();
});


How can I compact this? There HAS to be a simpler way!

Answer Source

Maybe you can use a helper function like this:

// events and args should be of type Array
function addMultipleListeners(element,events,handler,useCapture,args){
  if (!(events instanceof Array)){
    throw 'addMultipleListeners: '+
          'please supply an array of eventstrings '+
          '(like ["click","mouseover"])';
  }
  //create a wrapper for to be able to use additional arguments
  var handlerFn = function(e){
    handler.apply(this, args && args instanceof Array ? args : []);
  }
  for (var i=0;i<events.length;i+=1){
    element.addEventListener(events[i],handlerFn,useCapture);
  }
}

function handler(e) {
  // do things
};

// usage
addMultipleListeners(document.getElementById('first'),
                     ['touchstart','click'],handler,false);