PDA

View Full Version : jQuery Changing background indefinitely with jQuery and setTimeout


shmoyko
04-26-2010, 05:25 PM
Hello people,

I have a site http://insearchofsound.com/index.php

and I would like to change the background indefinitely every 10 seconds.

Here's the code

$(document).ready(function() {
//image index
var ii = 0;

//timer
var t;

//list of images
var imgs = ["bg1.jpg","bg2.jpg","bg3.jpg"];

loopBG(imgs,ii);

});

function loopBG(imgs,ii) {
$("pagewrapper").css("background-image","url(backgrounds/" + imgs[ii] + ")");
ii++;

if (ii == imgs.length) {
ii = 0;
}

t = setTimeout(loopBG(imgs,ii), 10000);

}


Two problems with this code: first, the backgrounds don't change at 10 second intervals (they don't change at all) and second, I get the "too many iterations" error after a few seconds.

Any solutions?

Many thanks

Shmoyko

Fumigator
04-26-2010, 08:13 PM
I've been using the jQuery plugin "timers", and it does the job perfectly. I leave a page up and running for days on end which refreshes the database via ajax every 5 seconds.

http://jquery.offput.ca/timers/

shmoyko
04-27-2010, 08:09 PM
Brilliant! Thank you very much.

Now, how would I reset the counter "i" after I reach the end of my image array?

Cheers,

Shmoyko


$(function() {

//list of images
var imgs = ["bg1.jpg","bg2.jpg","bg3.jpg"];

$("#pagewrapper").everyTime(10000,function(i) {
if (i == imgs.length) {
i = 0;
}

$(this).css("background-image","url(uploads/images/site_images/backgrounds/" + imgs[i] + ")");
});

});

Fumigator
04-27-2010, 08:23 PM
I would calculate the modulus of i (by dividing the number of elements in the array by i) and use the result as your array index.

I didn't test this but see if it works for you:


$(function() {

//list of images
var imgs = ["bg1.jpg","bg2.jpg","bg3.jpg"];

$("#pagewrapper").everyTime(10000,function(i) {
var mod = imgs.length % i;
$(this).css("background-image","url(uploads/images/site_images/backgrounds/" + imgs[mod] + ")");
});

});

shmoyko
04-29-2010, 02:23 PM
Good stuff.

The modulus approach works with a slight modification:


$("#pagewrapper").everyTime(2000,function(i) {

var mod = (i < imgs.length)? imgs.length % i : i % imgs.length;

$(this).css("background-image","url(uploads/images/site_images/backgrounds/" + imgs[mod] + ")");

});

Fumigator
04-29-2010, 04:41 PM
Oops, yeah, i % imgs.length is what I meant :p You really don't need to do anything different when i < imgs.length, it'll work for that range as well. I just goofed on the part that really matters! But glad you caught my intent and figured it out. :thumbsup:

shmoyko
05-05-2010, 02:10 PM
That works too :)

Just being cheeky here: would you know how to fade the background images in and out, or even cross-fade them?

Many thanks.