[thelist] Weird Javascript Problem

.jeff jeff at members.evolt.org
Sat Mar 2 14:24:01 CST 2002


r,

><><><><><><><><><><><><><><><><><><><><><><><><><><><><><
> From: R.Livsey
>
> In IE (havent tested with anything else yet) I get an
> error (Object Expected) for the following code :
>
> <script language="JavaScript1.2">
> //if browser supports window.innerWidth
> if (window.innerWidth)
>    document.write(window.innerWidth)
>
> //else if browser supports document.all (IE 4+)
> else if (document.all)
>    document.write(document.body.clientWidth)
> </script>
><><><><><><><><><><><><><><><><><><><><><><><><><><><><><

if this is in the head of the document then that's the cause of the error.
you're referencing the body before it's defined/rendered.  there are two
solutions.

1)  move the script out of the head into the body.  this
    isn't ideal if you're not going to continue using
    the document.write().

2)  move the checks inside a function that you call with
    the onload event handler.

<script language="JavaScript" type="text/javascript">
<!--
  function onLoad()
  {
    //if browser supports window.innerWidth
    if (window.innerWidth)
       document.write(window.innerWidth)

    //else if browser supports document.all (IE 4+)
    else if (document.all)
       document.write(document.body.clientWidth)
   }

   window.onload = onLoad;
// -->
</script>

i would suggest dropping the 1.2 from the language attribute value.  you're
already doing support detection, so it's unnecessary.  additionally, i'd add
the type attribute with a value of "text/javascript".  also, don't forget to
wrap the contents of the <script> block in html comments.  there aren't many
browsers around these days that don't understand <script> tags, but the
solution is so incredibly simple.  better safe than sorry.

><><><><><><><><><><><><><><><><><><><><><><><><><><><><><
> Im working on some javascript to gather browser details
> to be submitted to a database.
><><><><><><><><><><><><><><><><><><><><><><><><><><><><><

based on this, it seems option number 2 above would be the best solution.

good luck,

.jeff

http://evolt.org/
jeff at members.evolt.org
http://members.evolt.org/jeff/




More information about the thelist mailing list