views:

995

answers:

4
document.click = check;

function check(e)
{ 
    var obj = document.getElementById('calendar_widget');

    if (obj != 'null')
    {
     if (e.target.id != 'show_calender')
      obj.style.display='none';
    }
}

Error is in Internet Explorer: e.target.id is undefined.

+3  A: 

IE doesn't support the target property, they use srcElement instead.

Change:

if (e.target.id != 'show_calender')

to:

if ((e.target || e.srcElement).id != 'show_calender')

You may also need to add this to the beginning of your function:

if (!e) e = window.event

Your final code would look like this:

function check(e) { 
    if (!e) e = window.event;
    var obj = document.getElementById('calendar_widget');

    if (obj != 'null') {
        if ((e.target || e.srcElement).id != 'show_calender')
                obj.style.display='none';
    }
}
Prestaul
if IE doesn't support the `target` property, then your code `e.target.id` is going to be a null reference error as soon as IE hits it.
Crescent Fresh
I think `(e.target.id || e.srcElement.id)` will still throw an error in IE, as it will try to access the `id` property of the `target` property, but `target` does not exist.
Ionuț G. Stan
Good catch. I've fixed the issue.
Prestaul
+1  A: 

IE does not pass an event object as a parameter, the event object is accessed as a global identifier called event. Also it doesn't use the term target, instead it uses srcElement.

Hence the equivalent code for IE is:-

 function check()
 { 

    var obj = document.getElementById('calendar_widget');

    if (obj != 'null')
    {
        if (event.srcElement.id != 'show_calender')
            obj.style.display='none';
    }
 }

Its for this reason that Javascript frameworks such as JQuery are so popular.

AnthonyWJones
Thank you sir, its working. :)
coderex
+1  A: 

You've got a classic event handling cross-browser problem. I'd advice using a library such as Prototype, JQuery, YUI or MooTools for handling this in a much easier and straightforward manner. The problem is that IE does not pass the event object. Instead it can be found as a global object.

PatrikAkerstrand
+2  A: 

Internet Explorer doesn't pass the event object to the event handler - it sets it as a property of the window object instead. Also, it uses srcElement instead of target. Try


document.click = check;

function check(e)
{ 
    var target = e ? e.target : window.event.srcElement;
    var obj = document.getElementById('calendar_widget');

    if (obj != 'null')
    {
        if (target.id != 'show_calender')
                obj.style.display='none';
    }
}

NickFitz
Also, it's `document.onclick = ...`, not `document.click = ...`
Crescent Fresh
Oh, this jQuery... :)
Ionuț G. Stan