I have a header that has a css background image that I want to be side-scrolled at a rate of 1px every 50ms. However, the background image changes depending on the time on the users computer and I cannot work out how I would go about doing this. I did write the code for the side-scrolling itself, but nothing else.
The Javascript used to side-scroll (nothing else):
setInterval("mvheader()",50);
function mvheader () {
window.cssXPos=window.cssXPos+1;
if (window.cssXPos>=window.cssMaxWidth) {
window.cssXPos=0;
}
toMove=document.getElementById("header");
toMove.style.backgroundPosition=window.cssXPos+"px 0px";
}
The JavaScript used to use a different css file depending on the time:
function styleSwitcher() {
var currentTime = new Date().getHours();
if (0 <= currentTime&¤tTime < 6) {
document.write("<link rel='stylesheet' href='css/night.css' type='text/css'>");
}
if (6 <= currentTime&¤tTime < 18) {
document.write("<link rel='stylesheet' href='css/day.css' type='text/css'>");
}
if (18 <= currentTime&¤tTime <= 24) {
document.write("<link rel='stylesheet' href='css/night.css' type='text/css'>");
}
}
styleSwitcher();
The CSS (the only difference bewteen the other files is the folder name. night instead of day and vise versa):
#header {
background-image:url(../img/day/tile.png);
background-repeat:repeat-x;
position:absolute;
height:100px;
width:100%;
top:0;
left:0;
z-index:9;
}
All right, so there were couple of problems with your side-scrolling script:
setInterval("mvheader()", 50)it would work as expected, however using that syntax boils down to fact, that javascript has to interpret string passed as a first arguemnt. You can usesetInterval(mvheader, 50)as an equivalent – as you can see, you would now pass function as a parameter to setIntervalI’ve modified your code and you can check working version here: http://jsfiddle.net/wtk_pl/ydJhr/4/.
It’s working fine, however I’ve also created seconds, cleaner version that don’t pollute global scope with new variables and should perform better because I “cache” the
#headernode in a variable, rather than searching for it on every iteration of amvheader(). Check it out here: http://jsfiddle.net/wtk_pl/ydJhr/9/As to loading different css based on time of the day – It’s totally doable from javascript, however I would recommend you do that on server side (meaning determine and embed proper css file before sending page content to user) – why bother the client side script with that?