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!
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.
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.
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.
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); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With