Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the subtle cross-browser differences in Event Object

The following declaration at the window level:

    var event; // for IE
    var event = "anything"; // for Chrome

will destroy the event object as used here:

    <div onMouseOver = "alert(event.type);">Mouseover Div</div>

Firefox does not seem phased by either declaration.

I realize that declaring a variable with the name "event" is bad code but I am curious about the technical difference here, e.g. that the use of var in IE reinitializes the variable to null, whereas Chrome will not overwrite with a var declaration unless a value is explicitly assigned, and maybe FF holds the event object outside of the window's var declaration scope altogether.

This is more of a curiosity. I ran into a bug in IE on a site outside of my control that was caused by this and the more I looked into the more I saw subtle differences between browsers. Just wondering if anyone had any insights here.

like image 646
johnmdonahue Avatar asked Feb 03 '10 23:02

johnmdonahue


People also ask

Why is cross browser testing important?

Cross browser testing helps with that by pinpointing browser-specific compatibility errors so you can debug them quickly. It helps ensure that you're not alienating a significant part of your target audience–simply because your website does not work on their browser-OS.

How browser handle events?

Events are signals fired inside the browser window that notify of changes in the browser or operating system environment. Programmers can create event handler code that will run when an event fires, allowing web pages to respond appropriately to change.


2 Answers

In IE, event is a property of the window object and is used in event handlers functions to access the event being handled. In other browsers such as Firefox, the situation is that in an event handler attribute, the JavaScript code inside the attribute is called as though it forms the body of a function into which has been passed a parameter called event that corresponds to the event being handled. So in

<div onmouseover="alert(event.type);">Mouseover Div</div>

the mouseover code is effectively

function(event) {
    alert(event.type);
}

and the event parameter overrides any event declared in a containing scope, whereas in IE, it's

function() {
    alert(event.type);
}

and the event identifier is resolved as a property of the global object (i.e. window).

like image 187
Tim Down Avatar answered Nov 14 '22 23:11

Tim Down


The "event" object in IE is a property of the "window" object; that is, it's global. In Firefox, it's a value constructed and passed in to event handlers.

If you use jQuery or some other framework, usually the event handling support will normalize the "event" object into something that works identically across browsers.

like image 22
Pointy Avatar answered Nov 14 '22 23:11

Pointy