Click here to Skip to main content
15,896,154 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am using the following codes to swap images one after another but only the image mentioned in <img> tag is displayed. The images are not swaping as i want. please help me.

XML
<html>
<head>
<script language="javascript">
(function(){
 var rotator=document.getElementById('rotator');
 var imageDir='';
 var delayInSeconds=2;
 var images=['2.jpg','3.jpg','4.jpg','5.jpg','4.jpg'];

 var num=0;
 var changeImage=function(){
    var len=images.length;
    rotator.src=imageDir+images[num++];
    if(num==len){
        num=0;
        }
    };
    setInterval(changeImage, delayInSeconds * 1000);
    })();
</script>
</head>
<body>
    <img src="4.jpg" alt="rotating image" width="700" height="600" id="rotator">
</body>
</html>
Posted

1 solution

You are trying to get a reference to the image element in your main closure, before the document has loaded.

If you move the var rotator=... line inside the changeImage function, it should work.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900