Click here to Skip to main content
15,881,588 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have 3 pictures and I want them to change every 3 sec.

I have the following codes which also works but they re influencing some of my other codes. I don't know why.

Can someone help me with another solution.

I am not a programmer so please explain things easy. thanks

What I have tried:

Html

<script type="text/javascript">
var picPaths = ['iphone1.png','iphone2.png','iphone3.png'];
var curPic = -1;
//preload the images for smooth animation
var imgO = new Array();
for(i=0; i < picPaths.length; i++) {
imgO[i] = new Image();
imgO[i].src = picPaths[i];
}

function swapImage() {
curPic = (++curPic > picPaths.length-1)? 0 : curPic;
imgCont.src = imgO[curPic].src;
setTimeout(swapImage,2000);
}

window.onload=function() {
imgCont = document.getElementById('imgBanner');
swapImage();
}

</script>

body


<img id="imgBanner" src="" alt="" width="350" height="456" />




CSS

#imgBanner {
position:absolute;
right: 80px;
top:836px;
z-index:9999;
padding: 0;
}
Posted
Updated 7-Dec-21 1:47am

1 solution

You can utilize javascript's in-built method setInterval to accomplish this.

Here's a quick solution that I can think of,

Let me know if you 've any questions.

// Initialize images in an array
var picPaths = ['iphone1.png','iphone2.png','iphone3.png'];
// An index to track the contender image 
var imageIndex = 0;
var bannerImage; 

// An event callback for starting the interval
function startInterval() {
 setInterval(displayNextImage, 3000);
}

function displayNextImage() {
  bannerImage.src = picPaths[imageIndex];
  if(imageIndex === (picPaths.length-1)) {
    imageIndex = 0;
  }
  else {
    imageIndex = imageIndex + 1; // It can be replaced with imageIndex ++  
  }
}

window.onload=function() {
 bannerImage = document.getElementById('imgBanner');
 startInterval();
}
 
Share this answer
 
Comments
Karthik_Mahalingam 7-Sep-16 13:24pm    
5

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