DOM Traps and Pitfalls: Window.event
Window.event is a proprietary Microsoft Internet Explorer property which is only available while a DOM event handler is being called. Its value is the Event object currently being handled. (info from MDN)
Browser Compatibility
As window.event
is not part of any specification, Firefox does not implement it on purpose.
And because of popularity of IE in old days, Chrome, Safari and other browsers implement window.event
to keep compatibility with pages designed to run on IE.
Newer version of IE and Edge of course support window.event
.
You may use 'event' in window
to test support for window.event
.
Advice
Do NOT use window.event
or event
in event handlers to be compatible with all browsers.
Alternative
Then, how can we get current event in an event handler?
The answer is, it's passed as the first and the only argument to an event handler. For example,
window.addEventListener('click', function (ev) {
// Current event is passed as the first argument to event handler
console.log('ev: ', ev);
// Check that event is the only argument which gets passed to the handler
console.log('arguments: ', arguments);
// Check `window.event` (not available on Firefox)
console.log('window.event: ', window.event);
// Or simply `event` (not available on Firefox),
// if no other local variables are called `event`
try {
console.log('event: ', event);
} catch (ex) {}
// Check equality of `ev` and `window.event`
// (not equal in IE <= 10 and Firefox, equal in all other browsers)
console.log('ev ', ev === window.event ? '===' : '!==', ' window.event');
});
Compatibility Notes
For event handlers attached via attachEvent
(only available for IE <= 10) or GlobalEventHandlers such as document.onclick
(breaks only for IE <= 8), they get called with no arguments, so using something like function (ev) { ev = ev || window.event; /* other code */ }
is necessary if support for older versions of IE is required.