javascript/css: switch body background image
A friend asked me today to fix an ugly javascript code intended to detect the screenwidth and according to the available width, switch the background image.
this is what i came up with:
JavaScript:
-
// javascript background switcher by pixeline
-
-
function switchBckgrndImg(){
-
document.body.style.backgroundImage="";
-
// THIS BIT DETECTS THE AVAILABLE SCREEN SPACE AND ORIGINATES FROM http://www.quirksmode.org/viewport/compatibility.html
-
var x,y;
-
-
if (self.innerHeight) // all except Explorer
-
{
-
x = self.innerWidth;
-
y = self.innerHeight;
-
}
-
else if (document.documentElement && document.documentElement.clientHeight)
-
// Explorer 6 Strict Mode
-
{
-
x = document.documentElement.clientWidth;
-
y = document.documentElement.clientHeight;
-
}
-
else if (document.body) // other Explorers
-
{
-
x = document.body.clientWidth;
-
y = document.body.clientHeight;
-
}
-
// THE FOLLOWING assigns a background image to each resolution
-
myscreenWidth = x;
-
if(myscreenWidth <=800) { var myImg ="_img/w800px.gif";}
-
if(myscreenWidth <=1024) { var myImg ="_img/w1024px.gif";}
-
if(myscreenWidth <=1152) { var myImg ="_img/w1152px.gif";}
-
if(myscreenWidth <=1280) { var myImg ="_img/w1280px.gif";}
-
else { var myImg ="_img/w1600px.gif" };
-
// image switching occurs now !
-
document.body.style.backgroundImage="url("+myImg +")";
-
//alert("width = "+myscreenWidth);
-
}
-
-
function onResizeHandler()
-
{
-
// ALL FUNCTION CALLS TO PERFORM ON RESIZE...
-
switchBckgrndImg();
-
}
-
function onLoadHandler()
-
{
-
// ALL FUNCTION CALLS TO PERFORM ON LOAD...
-
switchBckgrndImg();
-
}
-
window.onresize = onResizeHandler;
-
window.onload = onLoadHandler;
it works more or less: if i resize the window, it does switch between 1280 and 1600px, but it does not go below...
personal note: i think it's the condition order that is wrong.
Author: pixeline
Date: May 16th, 2006
filed in: Development
Follow the discussion on this entry via RSS 2.0 feed.