Why is ‘event’ variable available even when not passed as a parameter?

Why is ‘event’ variable available even when not passed as a parameter?

It isn’t, reliably. That code will fail on Firefox, for instance. It wasn’t and used to fail on Firefox. Microsoft used a global event variable. DOM2 defined it as an argument to the handler. Chrome decided to throw MS-specific code a bone and do both. For a long time, Firefox did not. But the global was standardized as a legacy API for compatibility reasons (spec | MDN) and Firefox added it in v63, briefly put it behind a flag the user had to enable, and since v66 ships with it unflagged.

Even on the browsers where that code works, note that event will be a raw event object, not the jQuery-enhanced one. That means that, for instance, on IE8 you can’t call event.preventDefault because IE8 doesn’t supply that function. jQuery would if you accepted the argument, because jQuery provides an event object with standardized features even on browsers that are missing those features.

Leave a Comment