Reputation: 3
I want to add multiple listeners to my buttons using JavaScript ES6. I am following this guide
For some reason, it is not working for me.
HTML:
<input type="button" value="Button">
JavaScript:
function multipleEventsListeners(elem, events, func) {
events.split().forEach(e => elem.addEventListener(e, func, false));
}
const INPUT = document.querySelector('input');
multipleEventsListeners(INPUT, 'onclick ontouchstart', function(e) {
console.log(this.tagName);
});
Upvotes: 0
Views: 61
Reputation: 63524
1) split
should be split(' ')
to split on the space
2) Your events should be click
and touchstart
.
function multipleEventsListeners(elem, events, func) {
events.split(' ').forEach(e => elem.addEventListener(e, func, false));
}
const INPUT = document.querySelector('input');
multipleEventsListeners(INPUT, 'click touchstart', function(e) {
console.log(this.value);
});
<input type="button" value="Button">
Upvotes: 1
Reputation: 129
events
is passed in as a single string - I think the problem you are having is caused by not splitting this string correctly. Use ' '
as your split separator.
function multipleEventsListeners(elem, events, func) {
events.split(' ').forEach(e => elem.addEventListener(e, func, false));
}
Upvotes: 1