|
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:
The event handling section of the script is repeated below. The problem stems from Internet Explorer and Firefox handling click events differently.
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:
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:
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: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.
http://www.mastemplate.com