Background Change on Page Reload
Sometime when you are browing a web site, you notice that the background keeps changing on pages you are visiting or on each page reload (refresh), definitely you are wondering how did they do it. I’ll explain to you how you do this.
Before I start, you can download the code, a full example which will work on all browsers. regarding the compatibility, the code it self for changing the back ground works with all browsers, but in the example I’ve made there are few extra CSS code for cross browser compatible (dont worry, I’ll explain it below).
We will use simple java function (Math.ceil & Math.random) + CSS
We will began writing our index.html page
Now we will add the following Java function to the head section
<script type="text/javascript">// <![CDATA[ var totalCount = 8; function ChangeDIVback() { var num = Math.ceil( Math.random() * totalCount ); document.getElementById("background").style.backgroundImage='url(images/'+num+'.jpg)'; } // ]]></script>
The totalCount is number of images we have, after we generate the number (using the ceil & random) we will save the generated number in variable called num then we will use getElementById.style.backgroundImage to show the background, note that your images must be numberd from 1 to 8 jpg format, you can have lower than 8 but sometimes when you click refresh same background will appear.
Now we are going to call the function in the HTML file
<script type="text/javascript">// <![CDATA[ ChangeDIVback(); // ]]></script>
Now apply some CSS properties
.background { position:absolute; top: 0px; right: 0px; width: 1600px height: 100%; background-repeat:no-repeat; }
now its done, go to your HTML file and see how the background is changing on each page reload.
In my example you will find some extra code, because i am displaying an extra DIV with CSS3 properties, thats why there is two style sheet one for all browsers and the other one is for IE.
Hope that its clear and simple to the point.
Youre so cool! I dont suppose Ive read anything like this before. So nice to find somebody with some original thoughts on this subject. realy thank you for starting this up. this website is something that is needed on the web, someone with a little originality. useful job for bringing something new to the internet!