Wednesday, 21 October 2009

Window.Event support cross browser

Accessing window.event in Chrome, Safari and Opera


Something that I found out today, which you may or may not know related to events and browser support, is that the global event object used by Internet Explorer:

window.event

Is also supported in Chrome, Safari and Opera. I presumed Opera would support it as it also supports IE's event model as well as the DOM 2 model. By this I mean you can attach events using attachEvent or addEventListener as well of course using inline events e.g element.onclick=function(){}.

As addEventListener is the superior method this is why any custom addEvent function should always check for the standard option first before then checking for attachEvent and then reverting to DOM0 (if you require IE4 or NN4 support :) )

For Firefox when using inline Javascript event handlers you need to pass in the Event object as a parameter to any function you are calling. This is how I presumed the other standards compliant browsers would also work but it seems they support both methods. E.g in IE, Opera, Chrome and Safari both these methods work:

<input type="button" id="txtA" value="Click" onclick="Run();" />
<input type="button" id="txtA" value="Click" onclick="Run(event);" />


But in Firefox only the second method will work. The function called does a test for the window.event object to capture the event.type but in Firefox it uses the event parameter. On my example test you will notice the undefined messages when a test for window.event is carried out. 

For example you may have seen many a function like the following that handles both the window.event and event parameter:
function test(e){
// use the event parameter if passed otherwise
// use the global window.event object
e = e || window.event;
}
This may be old knowledge but it was new to me so I thought I would post it in case others didn't realise this event support. Also most developers have moved on from using inline event handlers to using unobtrusive Javascript and attaching events to the DOM after the HTML has loaded.

You can test this out here by running the following two test functions which will output some messages to a DIV container. This test should be carried out in multiple browsers especially Internet Explorer (IE), Chrome or Safari, Opera and Firefox. I haven't checked version support apart from IE 7,8, Chrome 3, Safari 4, Opera 10 and Firefox 3.5.









No comments:

Latest Cheap Amazon Goods