Skip navigation

Another Browser-Inconsistency

by Ryan Frishberg
Before we start on this script, let's review some JavaScript. Accessing the "innerWidth" of a window (the part that displays HTML content, aka, the "body"), is browser-dependent, like almost everything else we've talked about in this tutorial. In Netscape (NN 4 and NS 6), we use: window.innerWidth for the "innerWidth" (and window.innerHeight for the "innerHeight"). In IE, we use document.body.clientWidth for the "innerWidth" (and document.body.clientHeight for the "innerHeight"). So, to store this value into the variable, IW (for "innerWidth"), we could use:

if(window.innerWidth){
      var IW=window.innerWidth;
}else{
      var IW=document.body.clientWidth;
}


It's VERY important to note that when accessing document.body, the <body> must have partly loaded already; you must access it either inside the body tag or after the body tag has started loading, using onLoad or setTimeout().

Shorten it up

Ok, we've just created a script to store the browser's "innerWidth" as the variable, IW. However, that's an awfully long script for such a seemingly simple thing to do. Another alternative is the trinary operator (condition?statement if true:statement if false):

var IW=window.innerWidth ? window.innerWidth : document.body.clientWidth;

The trinary operator is a handy way to shorten simple if-else statements. I wouldn't recommend using it on "hard" if-else statements because it could get confusing.

Now let's go onto the scrolling script.

Next -->