July 7, 201016 yr hi guys can anyone tell me how to change my background image using javascript? i want to it to change every 10 seconds or so to another one people have given me links to sites but the code it gives isnt working for some reason thanks guys
July 7, 201016 yr Hi, What are the links that people have you given? Why the code isn't working? I guess it must be very simple code.
July 7, 201016 yr Author Hi, What are the links that people have you given? Why the code isn't working? I guess it must be very simple code. i got this given to me yeaterday but i put the code where it says to it doesnt work, this one changes everytime you refresh which i dont want, i would like it to change automatically while your still on the page My link
July 7, 201016 yr That's some pretty ancient code there, but it basically does the job. The main script (the one in the top box) needs a bit of tweaking to get it into a seperate function... and to remove the cloaking device (they're just pointless these days): <script type="text/javascript"> function randomImage() { // Start by making the array of images so that we can get the length afterwards var images = [ "zebra.jpg", "tiler3.jpg", "wicker3.jpg", "aaa4.jpg" ]; // Make a random number based on the size of the array. // Here I've put the Math.random() function straight in and I've subtracted 1 from the final result. // That's because the array has 4 entries, but they're 'zero indexed', meaning the entries are images[0], images[1], images[2] and images[3] var rand1 = Math.round(Math.random() * images.length) - 1; // Now we change the background image of the body tag to the random image. document.body.style.backgroundImage = images[rand1]; } // Now we need another function to call out first function every 10 seconds // The setInterval() function uses milliseconds, so 10 seconds is 10,000 miliseconds function backgroundChanger() { setInterval(randomImage, 10000); } </script> Now, just add that second function to the body tag -- but don't use document.write to do it! <body onload="backgroundChanger"> And that should do it
Create an account or sign in to comment