How to autorotate image in javascript??

Posted by prakashmondal5-21103 under JavaScript on 3/30/2014 | Points: 10 | Views : 663 | Status : [Member] | Replies : 2
I try this code, but doesn't work.......

My code is:

<html>
<head>
<title> Auto Change Background Color </title>
<style type="text/css">
div
{
height:320px;
width:100%;
}
</style>
<script type = "text/javascript">
var image = new Array ('pic-1.jpg', 'pic-2.jpg', 'pic-3.jpg', 'pic-10.jpg','pic-11.jpg');

var image_index = 0;
function ChangeBgImage ()
{
alert(image[image_index]);
document.getElementById("ddiv").style.backgroundImage="url(image[image_index])";
image_index++;
if (image.length == image_index)
{
image_index = 0;
}
}
setInterval( "ChangeBgImage()", 1000);
</script>
</head>
<body>
<div id="ddiv">
</div>
</body>
</html>

Please help me...........




Responses

Posted by: A2H on: 3/30/2014 [Member] [MVP] Silver | Points: 25

Up
0
Down
Hi,
You need to make a slight change in the line of code where you assign the background image to div.
Please change your code from
document.getElementById("ddiv").style.backgroundImage = "url(image[image_index])";

to
 document.getElementById("ddiv").style.backgroundImage = "url(" + image[image_index] + ")"; 


Your Complete Modified Code:
<html> 

<head>
<title> Auto Change Background Color </title>
<style type="text/css">
div
{
height:320px;
width:100%;
}
</style>
<script type = "text/javascript">
var image = new Array('pic-1.jpg', 'pic-2.jpg', 'pic-3.jpg', 'pic-10.jpg', 'pic-11.jpg');

var image_index = 0;
function ChangeBgImage() {
alert(image[image_index]);
// document.getElementById("ddiv").style.backgroundImage = "url(image[image_index])";
document.getElementById("ddiv").style.backgroundImage = "url(" + image[image_index] + ")";
image_index++;
if (image.length == image_index) {
image_index = 0;
}
}
setInterval("ChangeBgImage()", 1000);
</script>
</head>
<body>
<div id="ddiv">
</div>
</body>
</html>


You can find a working sample Demo in below link
http://jsbin.com/hukequta/2/edit

Please Mark My reply as Answer if it helps to resolve your issue


Thanks,
A2H
My Blog

prakashmondal5-21103, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Mattyclown on: 4/9/2014 [Member] Starter | Points: 25

Login to post response