Jquery loop through different backgrounds

I am trying to change different backgrounds for a div loop going through an array of images and timing it every 5 seconds.

here is my code:

function changeBG(){

     //array of backgrounds
     var array = ["test.jpg", "test2.jpg", "test3.jpg",];


     for ( var i=0, len=array.length; i<len; ++i){
         $('.round-mask').css('background-image', 'url("images/work/'+array[i]+'")');

      }

}

window.setInterval(changeBG(), 5000);

This does not work, I see that it is a loop, but I always get the third image.

Any idea?

Thanks in advance.

Mauro

+3
source share
5 answers

Try it ~

    <script  type="text/javascript">
    var now = 0;
    var int = self.setInterval("changeBG()", 1000);
    var array = ["001.jpg", "002.jpg", "003.jpg", ];

    function changeBG(){
        //array of backgrounds
        now = (now+1) % array.length ;
        $('.round-mask').css('background-image', 'url("' + array[now] + '")');
    }
</script>

and forget about it ~

 for ( var i=0; i<array.length; i++){
 $('.round-mask').css('background-image', 'url("images/work/'+array[i]+'")');

  }
+7
source

something like this should work:

var i = 0;

function changeBG(){

     //array of backgrounds
     var array = ["test.jpg", "test2.jpg", "test3.jpg",];



    $('.round-mask').css('background-image', 'url("images/work/'+array[i]+'")');

    if(i == array.length -1){
         i= 0;
    }
    else{
        i++;
    }


}
+2
source

It really worked. 2014.

var i =0 ;

//array of backgrounds
var array = [
    "1.jpg", 
    "2.jpg", 
    "3.jpg", 
    "4.jpg", 
    "5.jpg", 
    "6.jpg", 
    "7.jpg", 
    ];

function changeBG(){
    if ( i > array.length -1) {
        i = 0;
    }

    $('.slideContainer').css('background-image', 'url("img/backgrounds/'+array[i]+'")');
    i++;
}

window.setInterval("changeBG()", 5000);
0
source

try it

var i =0 ;

//array of backgrounds
var array = ["test.jpg", "test2.jpg", "test3.jpg"];

function changeBG(){
    if ( i > array.length -1) {
        i = 0;
    }

    $('.round-mask').css('background-image', 'url("images/work/'+array[i]+'")');
    i++;
}

window.setInterval(changeBG(), 5000);
-1
source
$(element).on("click",function(){
  $("<div>").css("background-image", "url("+array[(i-1)]+")");
if (i == array.length){
 i=1;
}
else {
 i++;
}
})

This is my edit, so it actually does. Or

$(element).css("background-image", "url("+array[(i-1)]+")");
i == bb.length ? i=1 : i++;
-1
source

All Articles