0

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);
});
  • this question was already posted here : https://stackoverflow.com/questions/8796988/binding-multiple-events-to-a-listener-without-jquery – Mister Jojo Nov 30 '18 at 23:12

2 Answers2

1

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));
}
nicktu12
  • 129
  • 4
1

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">
Andy
  • 61,948
  • 13
  • 68
  • 95