0

When I run it, the 1st image appears and after one second all I could see is a white blank screen. Nothing happens. I guess there's a problem in JavaScript code. Here's the code I tried..

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style type="text/css">
img {
    width: 582px;
    height: 306px;

}

</style>
</head>

<body>

<img src="image-slider-1.jpg" id="myphoto" />

<script type="text/javascript">

var image=document.getElementById("myphoto");
var imageArray=("image-slider-1.jpg","image-slider-2.jpg","image-slider-3.jpg","image-slider-4.jpg","image-slider-5.jpg");

var imageIndex=0;

function slide(){

image.setAttribute("src",imageArray [imageIndex] );
imageIndex++;
if(imageIndex>=imageArray.length) {
    imageIndex=0;

}
}
setInterval(slide,1000);

</script>
</body>
</html>

Any help is greatly appreciated.

1
  • 1
    I never new you could declare array using () instead of [] Commented Jul 18, 2015 at 14:21

2 Answers 2

1

Try this. It worked for me.

var speed = 3700;  //interval

var Pic = new Array();


Pic[0] = 'abc.jpg';

Pic[1] = 'def.jpg';

Pic[2] = 'ghi.jpg';
//add as many as you want

var t; //interval

var j = 0; 

var p = Pic.length;

var preLoad = new Array()

for (i = 0; i < p; i++)
     {

       preLoad[i] = new Image();

       preLoad[i].src = Pic[i];

 }

 // call this from your html as shown below 
  //<body onload="runBGSlideShow()">
 function runBGSlideShow(){

  if (document.body)
      {

         document.body.background = Pic[j];

         j = j + 1;

        if (j > (p-1))
           {
              j=0; //start from pic1 again
        }

        t = setTimeout('runBGSlideShow()', speed); 
}

}
Sign up to request clarification or add additional context in comments.

Comments

0

The following line is not doing what you expect:

var imageArray=("image-slider-1.jpg","image-slider-2.jpg","image-slider-3.jpg","image-slider-4.jpg","image-slider-5.jpg");

if you check the value of imageArray after this call, you will find just a string, containing "image-slider-5.jpg". (Why? See the workings of the comma operator in javascript.)

To properly declare an array of strings, use the [] notation:

var imageArray=["image-slider-1.jpg","image-slider-2.jpg","image-slider-3.jpg","image-slider-4.jpg","image-slider-5.jpg"];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.