Pawel P
Pawel P

Reputation: 25

Need to change jquery from random image to sequence

so it's pre loading images

  var headerImages = [
       'images/logoa.png',
       'images/logob.png',
       'images/logoc.png',
       'images/logod.png',
       'images/logoe.png',
       'images/logog.png',
       'images/logoh.png',
       /* 'images/logoi.png', */
       'images/test/logoa.png',
       'images/test/logob.png'];

and then picking a random one on each page scroll, how do I make it in sequence, meaning from top to bottom of the pre load?

....

jQuery.preLoadImages(headerImages);


jQuery(window).scroll(function() {
  jQuery('#sidebar').css('backgroundImage', 'url(' +
headerImages[Math.floor(Math.random()*headerImages.length)] + ')');
});

So I guess it's this part Math.floor(Math.random()*headerImages.length) but I have no idea what to do..

Thanks a lot for your help!

Upvotes: 0

Views: 310

Answers (3)

Naryl
Naryl

Reputation: 1888

headerImages seems to be an array so you should be fine if you do a loop from 0 to headerImages.lenght and do something like:

jQuery('#sidebar').css('backgroundImage', 'url(' + headerImages[x] + ')');

Inside the loop, where x is the variable you increment from 0 to max.

Upvotes: 1

Karl Johan
Karl Johan

Reputation: 4022

You could do it by storing the current image index in an variable and the adding at each scroll. Then setting it to zero when it reaches the end of the list:

jQuery.preLoadImages(headerImages);

    var index = 0; // set the variable

    jQuery(window).scroll(function() {
    jQuery('#sidebar').css('backgroundImage', 'url(' + headerImages[index] + ')');

    index ++; // add one to point to the next image on the next scroll

    if(index==headerImages.length) index = 0; // If the counter is at the end of the array then set it to zero again

});

Upvotes: 1

Liam
Liam

Reputation: 29714

var x =0;
jQuery(window).scroll(function() {
  jQuery('#sidebar').css('backgroundImage', 'url(' +
headerImages[x] + ')');
x++
if (x == headerImages.length)
{
 x =0;
}
});

Upvotes: 1

Related Questions