Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
116
rated 0 times [  121] [ 5]  / answers: 1 / hits: 37767  / 12 Years ago, tue, may 15, 2012, 12:00:00

i want to loop a series of images in javascript. below is the code i have so far



<html>
<head>
</head>

<body>
<img src=images/image1.jpg alt=rotating image width=600 height=500 id=rotator>

<script type=text/javascript>
(function() {
var rotator = document.getElementById('rotator'); // change to match image ID
//var imageDir = 'images/'; // change to match images folder
var delayInSeconds = 1; // set number of seconds delay
// list image names
var images = ['1.jpg','2.jpg', '3.jpg', '4.jpg'];

// don't change below this line
var num = 0;
var changeImage = function() {
var len = images.length;
rotator.src = images[num++];
if (num == len) {
num = 0;
}
};
setInterval(changeImage, delayInSeconds * 50);
})();
</script>
</body>
</html>


It can only display the image i have declared in the var image. if i have 10000 image , how to do that . I have tried using a 'for' loop but it failed .. any suggestions ?? thanks in advance



==============================================================



update version that Joseph recommend :



<html>
<head>
</head>

<body>
<img src=images/1.jpg alt=rotating image width=600 height=500 id=rotator>

<script type=text/javascript>
(function() {
var rotator = document.getElementById('rotator'), //get the element
var delayInSeconds = 1, //delay in seconds
var num = 0, //start number
var len = 9999; //limit
setInterval(function(){ //interval changer
num = (num === len) ? 0 : num; //reset if limit reached
rotator.src = num + '.jpg'; //change picture
num++; //increment counter
}, delayInSeconds * 1000);
}());
</script>
</body>
</html>

More From » loops

 Answers
29

Assuming that images have the same sequential filenames, this would be best when looping through a lot of them:



(function() {
var rotator = document.getElementById('rotator'), //get the element
dir = 'images/', //images folder
delayInSeconds = 1, //delay in seconds
num = 0, //start number
len = N; //limit
setInterval(function(){ //interval changer
rotator.src = dir + num+'.jpg'; //change picture
num = (num === len) ? 0 : ++num; //reset if last image reached
}, delayInSeconds * 50);
}());

[#85576] Monday, May 14, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
makaylahk

Total Points: 166
Total Questions: 94
Total Answers: 117

Location: Gabon
Member since Sat, Jul 25, 2020
4 Years ago
;