Why is 'event' variable available even when not passed as a parameter?
I wonder why does the following code work in some browsers? I.e. even when there's no parameter to a click()
function however event
variable exists and dosomething
method is called on the event trigger object?
$(<selector>).click(function () {
$(event.target).<dosomething>
});
Solution 1:
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.