Alejandro Veintimilla
Alejandro Veintimilla

Reputation: 11523

Change img src every second using Jquery and Javascript

I have been trying to write a script that changes an image src every two seconds based on a list.

So, everything is inside a forloop that loops over that list:

$(document).ready(function() {
    var lis = {{dias|safe}}; <----- a long list from django. This part of the code works fine.

    for (i=0; i<lis.length; i++){
        src_img = lis[i][1];
        var timeout = setInterval(function(){
            console.log(src_img)
            $("#imagen").attr("src", src_img);
        }, 2000)
    }
});

It doesn't work, the console logs thousands of srcs that correspond to the last item on the list. Thanks a lot for your help.

Upvotes: 1

Views: 1828

Answers (3)

patricK
patricK

Reputation: 1105

You need something like this

$(document).ready(function() {
    var index = 0;
    setInterval(function(){
         src_img = lis[index++ % lis.lenght][1]; // avoid arrayOutOfBounds 
         $("#imagen").attr("src", src_img);
    }, 2000)
});

Upvotes: 1

sidhartha madipalli
sidhartha madipalli

Reputation: 623

var curentImage = 0;
var length = lis.length;

function NewImage(){
    var url = lis[curentImage];
    if(curentImage < length){
         currentImage++;
    }
   else{
      currentImage = 0;
    }
return url;
}

var timeout = setInterval(function(){
        $("#imagen").attr("src", getNextImg());
}, 2000)

PS: Better than the previous one, Checks for lis length and starts from first if you reach end.

Upvotes: 1

shershen
shershen

Reputation: 9993

you don't need to run cycle in this case, you just save "pointer" - curentImage and call next array item through function ever 2 sec

 var curentImage = 0;

 function getNextImg(){
    var url = lis[curentImage];

    if(lis[curentImage]){   
    curentImage++;
    } else {
    curentImage = 0;
    }

    return url;
 }

var timeout = setInterval(function(){
            $("#imagen").attr("src", getNextImg());
        }, 2000)

Upvotes: 3

Related Questions