Shaun Mccran

My digital playground
 
14
A
P
R
2010

Handling JavaScript event model differences in Internet Explorer and Firefox

A few weeks ago I created an inline editing system for a Content Management System. It allowed a user to click on a page element and edit it inline. The updated data was then submitted through an AJAX request.

I have recently discovered an issue with some of the JavaScript code that I wrote in the event handling routine.

The original article is here:

http://www.mccran.co.uk/index.cfm/2010/2/10/Dynamically-editing-web-content-inline-using-JavaScript-and-AJAX

The event handling section of the script is repeated below. The problem stems from Internet Explorer and Firefox handling click events differently.

view plain print about
1function getId(e) {
2    var targ;
3    if (!e) var e = window.event;
4    if (e.target) targ = e.target;
5
6    else if (e.srcElement) targ = e.srcElement;
7
8    if (targ.nodeType == 3) // defeat Safari bug
9        targ = targ.parentNode;
10
11    //thisTarget = e.target.id; // FF
12    //thisTarget = e.srcElement.id; //IE
13
14    thisTarget = clickHandler(e)
15    //alert(thisTarget);
16}

Examining the code above I can see that to track event handling in Internet Explorer I need to use:

view plain print about
1e.srcElement.id

This is because IE uses the window.event model, whereas all other browsers intrinsically handle the event model. This means that you can just say:

view plain print about
1e.target.id

As Firefox will automatically resolve the 'target' value.

The Fix

To create a cross browser script that will work in both Internet Explorer and Firefox we can use the returned value from a function like this:

view plain print about
1function clickHandler(e) {
2return (window.event) ? window.event.srcElement.id : e.target.id;
3}

This function will evaluate the response of two arguments from a switch statement. Each browser will only understand one of each of these statements, so the browser will only return the value of the statement it understands (Both statements return the same calculated value).

And that is a cross browser Event handling script.

TweetBacks
Comments

This content is purely my opinon, any offence or errors are unintentional, please comment your views appropriately
Site Credits
Aggregated by ColdfusionBloggers.org Powered by Coldfusion

Technology & Science Blogs - BlogCatalog Blog Directory Blog Directory & Search engine