Alejandro Alejandro - 1 month ago 7
CSS Question

Random CSS background image

I can't find anything that works for me, and since I'm a cut and paste html editor (I know only the main basic stuff), I don't understand most of the other posts. This is the webpage I'm working with: http://goo.gl/MgsoX4 (I'm hosting it on dropbox because I haven't finished it yet). I had the idea of having a background change every time some refreshed/reloaded the page. I can't seem to find anything that works for me. The CSS for the background is the following:

#banner {
background-attachment: scroll, fixed;
background-color: #666;
background-image: url("images/overlay.png"), url("../images/1.jpg");
background-position: top left, center center;
background-repeat: repeat, no-repeat;
background-size: auto, cover;
color: #fff;
padding: 12em 0 20em 0;
text-align: center;
}


Whenever I change "../images/1.jpg" to "../images/2.jpg", the background will change to the second jpg, but I've tried a php image rotator and it won't work!

Answer

If you want to use JQuery you can paste this code in the head section of your html page or just before the closing tag of your page.

I dowloaded your files and changed the file path for the img and it worked fine for me. everytime I hit f5 you will get a new background image

     <!-- place in head element or before closing-->  <!-- </body> tag of html page -->



 <!--load JQuery first-->
 <script src="//code.jquery.com/jquery-1.10.2.js"></script>

      <script>
$(document).ready(function(){

//the highest number of the image you want to load
var upperLimit = 10;

//get random number between 1 and 10
//change upperlimit above to increase or 
//decrease range
var randomNum = Math.floor((Math.random() * upperLimit) + 1);    


 //change the background image to a random jpg
 //edit add closing )  to prevent syntax error
 $("body").css("background-image","url('images/" + randomNum + ".jpg')");//<--changed path




 });
 </script>