views:

46

answers:

1

For some reason the following code does not work as expected when in IE 8, as noted in the comment. I'm trying to add a "writeSpecial" method to the document object, and this works fine the first time that the method is called, but whenever this is called a subsequent time, it becomes undefined.

However, this only happens in IE when I use the onload event. There seems to be no difference between an inline body onload and window.attachEvent('onload', main);. If I call main() directly from the script block, it works fine. Again, this is only in IE.

Would anyone happen to know why this is?

Thanks!

<html>
  <head>
    <title>Test</title>
    <script type="text/javascript">

      document.writeSpecial = function(str)
      {      
        this.write(str + " [specialfied]");
      }          

      function main()
      {           
        alert(document.writeSpecial);
        document.writeSpecial('test 1');
        alert(document.writeSpecial);    //document.writeSpecial is undefined here in IE, works in firefox...why?
        document.writeSpecial('test 2');        
      }    
    </script>
  </head>
  <body onload="main()">
  </body>
</html>
A: 

I did some testing and as near as I can figure in IE document.write resets the document object. So here is a revised version that will work. If you didn't use the write function I don't think you would have had any trouble. Maybe someone else can elaborate on why IE does this.

window.onload=function(){
function foo(str){
  document.write(str + " [specialfied]");
  document.writeSpecial=foo;
}
document.writeSpecial=foo;
main();
function main(){
  document.writeSpecial('test 1');
  document.writeSpecial('test 2');        
}};
qw3n
A possible workaround (though I don't know for sure if it would work): Don't use document.write. Use `[body].innerHTML +=` instead.
MatrixFrog
It would work as well, but I'm not sure exactly what writeSpecial() is supposed to do so I'm not sure which is the better solution.
qw3n
Thanks for the responses :). This is just an oversimplified example, taken out of context to illustrate what I had observed. For all practical purposes, there are a few different ways that I can work around the issue. I was mainly interested in an explanation for this behavior.
Lonimor