Can I combine event listeners with the same target element?

... and callback method?

input_element.addEventListener("paste", self.hide, false);
input_element.addEventListener("keypress", self.hide, false);
input_element.addEventListener("drop", self.hide, false);

to a form like this -

input_element.addEventListener("paste keypress drop", self.hide, false);

I checked MDN and the API does not support this form, but is there any other way?

+4
source share
2 answers

A few years later, I don’t see what is the difference between the example in the question and what I wrote, so this update

["paste", "keypress", "drop"].forEach(event => input_element.addEventListener(event, self.hide, false));

ORIGINAL RESPONSE

The first thing that came to mind

function hide(){
    self.hide();
}

input_element.addEventListener("paste", hide, false);
input_element.addEventListener("keypress", hide, false);
input_element.addEventListener("drop", hide, false);
+3
source

The obvious point of DRY is to declare a function once:

var updateFn = function () {
    self.hide()
};
input_element.addEventListener("paste", updateFn, false);
input_element.addEventListener("keypress", updateFn, false);
input_element.addEventListener("drop", updateFn, false);

There are other ways to do this, but they are probably not very reasonable for you.

+1
source

Source: https://habr.com/ru/post/1543902/


All Articles