I'm trying to change the background image of a page (with setInterval eventually, but this is just a button to test it for now). The background image is appearing fine, and the alternate image is nice.
It's not working. I've also had referred to the background image in onclick as [ICODE]document.body.background[/ICODE] and [ICODE]document.body.backgroundImage[/ICODE].
Exactly, you need to use the same syntax as the CSS, in other words surround the value with url().
In an unrelated note, for terseness and to create smaller file downloads, the CSS for your body' background should be combined into the shorthand property: background. Like this:
I have been using that to check that I was able to change the background regularly as a sort of animation using this where backg() is fired on body load:
Code:
<script type="text/javascript">
function backg() {
setInterval(tail(), 2000);
}
function tail() {
document.body.style.backgroundImage = 'url(img/backg.jpg)';
setTimeout("document.body.style.backgroundImage = 'url(img/backg1.jpg)';", 1000);
}
</script>
As it stands, this has the effect of changing the background once, but then it stops. It's as if tail is called once, but not repeated. In fact, I'm pretty sure that's happening because I reversed the image references (i.e. backg1 being set first and then backg being set), which works.
but really I think you can simplify - put your image paths in an array, set the interval on body load and let the code do the rest, this way you can add as many images as you like to the loop, just by adding their paths to the array:
Bookmarks