Why am I getting an error for this piece of code?:
function catchevent()
{
eventSrcID=(event.srcElement)?event.srcElement.id:'undefined';
eventtype=event.type;
status=eventSrcID+' has received a '+eventtype+' event.';
}
Firefox says that event is not defined. Actually, this is copied from here and it clearly says that it is for IE5. I use Firefox 3.6.13 on Ubuntu.
My Question is not why it doesn’t work on my browser. Instead, is there a way to define event object, as suggested by the link, that would work for my browser?
UPDATE
Why isn’t this working
<html>
<head>
<script>
function catchevent( e ) {
// reference the proper event object
var e = e || window.event;
// reference the proper target
var srcElem = e.target || e.srcElement; //line no 9
// get the id of the target
var eventSrcID = srcElem.id;
alert(eventSrcID);
}
</script>
</head>
<body>
<a id="link1" href="#" onclick="catchevent()">link1</a>
<a id="link2" href="#" onclick="catchevent()">link2</a>
<a id="link3" href="#" onclick="catchevent()">link3</a>
</body>
</html>
For this i am still getting error on line no 9
e is undefined
[Break On This Error] var srcElem = e.target || e.srcElement;
Now how do I need to pass event object on catchevent() or is there some mistake? please suggest.
In Firefox and other W3C compliant browsers, the handler function will receive an event object as an argument to the function.
IE uses a global
eventobject.Here’s a cross browser solution for your code.
You’ll notice I used the
varkeyword when creating variables. You should do this, otherwise you’re creating global variables.Also note that the keyword
thiswill be a reference to the element to which the handler was assigned.