Search code examples
javascriptjquerydom-eventsonbeforeunloadonunload

addEventListener Problems in IE


Possible Duplicate:
MSIE and addEventListener Problem in Javascript?

I am trying to listen for a close event on a child popup window that is called by its parent page. The idea is for a user to be able to fill out a form and then using a popup window accept permissions for and upload a video to YouTube.

The function I currently have works with Chrome but I cannot seem to get it to work on IE 8?

function ShowUploadVideoPopUp(URL){
    //get the top and left position that the popup should be placed in
    //half the screen width and height to center the popup
    var top = Math.max(0, (($(window).height()) / 2) + $(window).scrollTop()) - 210;
    var left = Math.max(0, (($(window).width()) / 2) + $(window).scrollLeft()) - 300;
    //generate an id for this popup
    day = new Date();
    id = day.getTime();
    //open the window
    var win = window.open(URL, id, 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=600,height=420,left = ' + left + ',top = ' + top);
    //we need to set a timeout otherwise the unload event is called before the window is opened
    //dont ask me why!?!
    setTimeout(function(){
        //add an event listener to listen for closure of the popup window
        //call the video uploaded function when the window is closed
        win.addEventListener("unload", VideoUploaded, false);
    }, 500);
    return false;
}

The idea is that once the popup has closed I can submit a form on the parent page.

The error I get is:

'Object doesn't support this property or method'

which I guess means that me assigning the created window does not support me calling the addEventListener method.

Your help with this would be appreciated.


Solution

  • IE < 9 doesn't support addEventListener instead use attachEvent

    setTimeout(function(){
        if(win.addEventListener) // w3c standard
            win.addEventListener("unload", VideoUploaded, false);
        else if win.attachEvent('onunload', VideoUploaded, false); // IE
        else win.onunload=VideoUploaded;
    }, 500);
    

    Here is an answer on SO.