-1

what i am using right now

window.addEventListener("touchend", myFunction);
window.addEventListener("load", myFunction);

I want to know a way to add it in one line, since OR doesn't work,

window.addEventListener("load"||"touchend", myFunction);
  • As far as I know in vanilla JavaScript, each event type requires its own event listener. Unfortunately, you can’t pass in multiple events to a single listener like you might in jQuery and other frameworks. – Harry Joy Oct 07 '19 at 05:54
  • `['load', 'touchend'].forEach(function(e) { window.addEventListener(e, myFunction); });` – mplungjan Oct 07 '19 at 05:56
  • @mplungjan THANK YOU THIS WORKS PERFECTLY! – Parilega Deg Oct 07 '19 at 06:09

2 Answers2

0

According to this https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener it's not allowed

R.Groote
  • 88
  • 7
0

Type is a case-sensitive string representing the event type to listen for. You can not define multiple conditions in it.

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Parameters

But you can apply multiple listeners to the same function like this:

function addMultipleListeners(eventNames) {
    var events = eventNames.split(' ');
    var eventsLength = events.length;
    var i;
    for (i = 0; i < eventsLength; i++) {
        window.addEventListener(events[i], myFunction);
    }
}

addMultipleListeners('mousemove touchmove');

I hope, it helps you.

Sami Ahmed Siddiqui
  • 2,328
  • 1
  • 16
  • 29