Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 812
coiso Avatar asked Aug 07 '12 12:08

coiso


People also ask

Can you add multiple event listeners to an element?

You can add many event handlers to one element. You can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements.

Can you have multiple event listeners on the same event?

We can add multiple event listeners for different events on the same element. One will not replace or overwrite another. In the example above we add two extra events to the 'button' element, mouseover and mouseout.

Can event listeners be nested?

The final step, the callback function, can be written as a nested anonymous function inside the event listener or can be a designated function fully defined in a separate function. The callback handles the resulting work you want to happen after an event has occurred.


1 Answers

I know this is an old question, but I thought some might find this approach useful; it could be applied to any similarly repetitive code:

ES6

['click','ontouchstart'].forEach( evt =>      element.addEventListener(evt, dosomething, false) ); 

ES5

['click','ontouchstart'].forEach( function(evt) {     element.addEventListener(evt, dosomething, false); }); 
like image 163
Allan Nienhuis Avatar answered Oct 28 '22 20:10

Allan Nienhuis