Change the Background image randomly after refresh the page using Javascript

In this post i will tell you how to change the background image after each refresh using simple javascript. This is one of the simple logic to create a random number and add this number to replace the background image and apply the new background image in next refresh the page. This script will work each refresh.

Below image shows the changing background image and below is the full source code you can use this code as you want. And also included the demo page for reference. I hope this example is very useful to you.

Code for change background image randomly:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta HTTP-EQUIV="REFRESH" content="5">
<title>Change Background image afer refresh the page...</title>
<script type="text/javascript"> 
var bgcount = 6;
function changebg() {
var num =  Math.ceil( Math.random() * bgcount );
document.body.background = 'img/'+num+'.jpg';

<div id="main" class="bg">
<h2 align="center" style="line-height:30px;"> Refresh the page to change the Background image  Or Wait 5 sec page will automatically refresh and you can see the background changes.</h2>
<h3 align="center">  <a href=""> </a></h3> 
<script type="text/javascript"> 

Post a Comment