coiso coiso - 1 year ago 94
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


Here is the original code:

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

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

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

function handler(e) {
  // do things

// usage
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download