Thursday, July 5, 2012

Background Image Change on Refresh with Javascript


The tutorial contains a folder called bgimages with background images files.
index.html
bgimages
-- 1.jpg
-- 2.jpg
-- 3.jpg
-- ....
-- ....

Javascript
Here variable totalCount is number of backgrounds. The Math.random() method returns a random number between 0 and 1 and the Math.ceil() method rounds a number towards to the nearest integer, and returns the result.
<html>
<head>
<script type="text/javascript"> 
var totalCount = 8;
function ChangeIt() 
{
var num = Math.ceilMath.random() * totalCount );
document.body.background = 'bgimages/'+num+'.jpg';
document.body.style.backgroundRepeat = "repeat";// Background repeat
}
</script>
</head>
<body> 
// Page Design 
</body> 
<script type="text/javascript"> 
ChangeIt();
</script> 
</html>

No comments:

Post a Comment