Gabotronix's avatar

Javascript: adding a single function to multiple events

Hi everybody, currently I have something like this:

window.addEventListener('load', function() {
        self.checkIsMobile();
    });

    window.addEventListener('resize', function() {
        self.checkIsMobile();
    }); 

Is it possible to do the same action for multiple events in a single line, something like:

window.addEventListener(['load', 'resize'], function() {
        self.checkIsMobile();
});

Thnaks in advance

0 likes
3 replies
DavidPetrov's avatar

Can't you just specify your function as a variable and then register a listener for your events inside of a foreach loop using that function?

Cronix's avatar

You also don't need a callback for those since all you are doing is calling a function and not passing anything to it. Just use the function name to call.

window.addEventListener('load', checkIsMobile);
window.addEventListener('resize', checkIsMobile);

Please or to participate in this conversation.