Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
});
like image 645
Sergey Pauk Avatar asked Oct 16 '15 09:10

Sergey Pauk


People also ask

What is the event parameter?

Understand event parameters Parameters provide additional information about the ways users interact with your website. For example, when someone views a product you sell, you can include parameters that describe the product they viewed, such as the name, category, and price.

What is event variable?

OverviewGlobal VariablesEvent Variables. Some events in AutoPlay Media Studio contain variables whose values are automatically set whenever that event is triggered. These variables are called event variables. Event variables are local to the event and can be found on some page and object events.

What is e in Eventlistener in JS?

The parameter e that you are asking about is an Event object, and it represents the event being fired which caused your function to be executed. It doesnt really have to be e , you can name it anything you want just like all other function parameters.

What does function e mean in Javascript?

"function(e)" is the event handling function (on event, object is created). "e" is the object handler (object is made accessible).


1 Answers

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.

like image 54
T.J. Crowder Avatar answered Sep 23 '22 14:09

T.J. Crowder