Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is 'event' available globally in Chrome but not FF?

While working on an answer for another question, a strange bug came up related to the event object being available in an anonymous function without being passed in. In Chrome the below works fine, but Firefox throws an error.

$(document).ready(function() {
  $("#uspsSideboxTrackingClose").click(function() {
    event.preventDefault();
    console.log(event);
  });
});

Chrome:

enter image description here

FireFox:

ReferenceError: event is not defined


It is already known that

$("#uspsSideboxTrackingClose").click(function(event) { .. }

works in both browsers. Here is the offending code. Is this a bug with Chrome or Firefox, or intended behavior by both browsers? Which browser is right?

like image 867
Drakes Avatar asked May 11 '15 02:05

Drakes


1 Answers

In IE, the event object was a global object, (which is not passed to the handler function) but accessed as a global object. You can also access it as a property of the window object like window.event

In in FF and other browsers the event object was passed as an argument, since in FF there is no global property called event, you are getting the error message.

In chrome they have added support for both these features, so you will get the event object as a global reference and as an argument.

But since you are using jQuery, jQuery normalizes these 2 behaviors and will always pass the event object as an argument to the event handler.

$(document).ready(function () {
    $("#uspsSideboxTrackingClose").click(function (event) {
        event.preventDefault();
        console.log(event);
    });
});
like image 199
Arun P Johny Avatar answered Sep 21 '22 08:09

Arun P Johny