Forum Moderators: open
When switching to unobtrusive javascript in IE, I can't seem to access the srcElement of an event anymore.
Example:
<!-- example 1 - this works in ie -->
<html>
<head>
<title>Page</title>
<script>
function testFunction(event) {
alert("event.srcElement.id="+event.srcElement.id);
}
</script>
</head>
<body>
<img id="testimage" src='someimage.jpg' onclick="testFunction(event)" />
</body>
</html>
<!-- example 2 - this doesn't work in ie, says srcElement cannot be found-->
<html>
<head>
<title>Page</title>
<script>
window.onload = function() {
var node = document.getElementById("testimage");
node.onclick=testFunction;
}
function testFunction(event) {
alert("event.srcElement.id="+event.srcElement.id);
}
</script>
</head>
<body>
<img id="testimage" src='someimage.jpg' />
</body>
</html>
I assumed that the two techniques would be synonymous, but apparently not. Can anyone help shed some light on why this is happening, and maybe give a (hopefully unobtrusive) solution? Thanks in advance.
function testFunction(event) {
Also, try changing this argument name to "e" (it may be confusing IE)
When you declare the onclick, try something like this:
if(navigator.appName=="Microsoft Internet Explorer")
{
node.onclick=new Function("testFunction(event)");
}
else
{
node.onclick=testFunction;
}
In standards browsers, the event object is passed as an argument to functions assigned as event handlers. The exception is when the event handler is inline. In this case, you need to use the keyname, event, in the event handler to place the event. For this coincedental reason, the syntax in inline event handlers is the same in all browsers.
Standards event objects don't have a srcElement property, instead they have a target property. It's worth noting that this is a node, not specifically an element, so it may return a text node in some cases. No risk of that here.
!* Change ¦ symbol to unbroken pipe (or it won't work) *!
window.onload = function() {
document.getElementById("testimage").onclick=testFunction;
}function testFunction(e) {
// e isn't passed by IE
e = e¦¦event;
alert("The source element's id is: "+ (e.srcElement¦¦e.target).id)
}
Thanks for your responses. I ended up with the following solution.
<!-- example 3 - unobtrusive - works in ie -->
<html>
<head>
<title>Page</title>
<script>
window.onload = function() {
var node = document.getElementById("testimage");
node.onclick=testFunction;
}
function testFunction(evt) {
if(evt)
alert("evt.target.id="+evt.target.id);
else //IE
alert("window.event.srcElement.id="+window.event.srcElement.id);
}
</script>
</head>
<body>
<img id="testimage" src='someimage.jpg' />
</body>
</html>