JavaScript for WordPress Forums Vanilla JavaScript Lesson 1.4.3 – Global event handlers Reply To: Lesson 1.4.3 – Global event handlers

#27529
Zac Gordon
Keymaster

GREAT Question!

This is due to the magic that browsers, or the engines they use, bring to the table.

Chrome, for example, automatically makes the event object available for you to use with the name ‘events’ in a function hooked up to an event this way.

Firefox on the other hand does it a little differently and makes it available as the first value in an arguments array that it passes to functions hooked to events. So you could do this for Firefox:


var myFunc = function() {
   eventObj = arguments[0];
}

element.onclick = myFunc;

For this reason you may sometimes see some code like this checking to see which approach is being taken and assigning that to a variable called events. This will work for Chrome or Firefox (and most other browsers).


var myFunc = function() {
   eventObj = arguments[0] || events;
}

element.onclick = myFunc;

The most common solution though is just to assign whatever is being automatically passed into your function with the name ‘events.’ You can do that this way:


var myFunc = function( event ) {
  console.log( event );
}

element.onclick = myFunc;

This way whether ‘events’ is passed or ‘arguments[0]’ it is still made available as events.

So folks prefer naming it ‘e’ to avoid confusing it with the native name something like Chrome would use.


var myFunc = function( e ) {
  console.log( e );
}

element.onclick = myFunc;

Hope that explains things a little better!!!