frenchie frenchie - 3 months ago 21
jQuery Question

Using window.onkeyup in two different javascript files

I have a web app that uses multiple javascript files. I have two event handlers like this in two files:

window.onkeyup = function (e) { SomeFunction1(e) }
window.onkeyup = function (e) { SomeFunction2(e) }


SomeFunction1
is in a file that's used in every part of the site but
SomeFunction2
is in a file that's only used in one part of the site.

The problem is that when I include the javascript file that contains the handler for
SomeFunction2
, it replaces the handler for
SomeFunction1
, which means the event doesn't trigger any more.

Instead of replacing the
window.onkeyup
handler, I want to add another handler in the javascript file that contains
SomeFunction2
so that both functions are called. How can I do that? JQuery available.

Thanks.

Answer

You can use on event function for this:

$(window).on('onkeyup', SomeFunction1);
$(window).on('onkeyup', SomeFunction2);

Or using vanilla JS

window.addEventListener('onkeyup', SomeFunction1);
window.addEventListener('onkeyup', SomeFunction2);