I'm new to javascript and was just wondering the best way to go about changing the background image (only 2 images) of a DIV say like every 10 seconds. Thanks :)
6 Answers
This should do it for you : http://jsfiddle.net/U9GCM/
$(document).ready(function(){
var setFirst = $('.set').first();
setFirst.addClass('active');
setTimeout(function(){change_background();},1000);
});
function change_background(){
var setFirst = $('.set').first(),
setActive = $('.active'),
setNext = setActive.next(),
setCheckActive = setActive.attr('id'),
setCheckLast = $('.set').last().attr('id');
if(setCheckActive == setCheckLast){
setNext = setFirst;
}
$('.active').removeClass('active');
setNext.addClass('active');
setTimeout(function(){change_background()},1000);
}
You can add as many divs as you want, just change 1000 to 10000 for ten seconds.
Hope it helps.
1 Comment
HAWKES08
thanks. how would i change a div inside the div background image too at the same time?
Try something like this:
$(document).ready(function(){
setTimeout('setbackground()',10000);
});
function setbackground(){
// change you image here
setTimeout('setbackground()',10000); // to change the image in 10 seconds
}
2 Comments
HAWKES08
i need the image to swap back too
David Laberge
The function call it self back. You would need to test the current display, then change it for the following one.
alternate CSS classes (ie bg1 <--> bg2) with a setInterval function
var body = document.getElementsByTagName('body')[0],
switchBG = function() {
var bgTimer = setInterval(function() {
body.className = (body.className === "bg2" ? "bg1" : "bg2");
}, 10000 /* 10000 ms = 10 sec */);
};
switchBG();
this is straight js
Comments
$(document).ready(function(){
var i = 0;
var images = newArray("image1.jpg","image2.png","image3.jpg");
setTimeout('changeBack(i, images)',10000);
});
function changeBack(i, images) {
i++;
if(i > images.length) {
i = 0;
}
$('#changeBackInThisId').css('background-image', images[i]);
setTimeout(changeBack(i, images), 10000);
}
I hope it works :-)
Or you can have any number of divs in your code with style="display: none" (besides the first of them) and each 10 seconds sets display: block; to one of them.
Comments
var time = 10000; // Ten seconds
var timer = setInterval(function() {
$('#myDiv, #myOtherDiv').css('background-image', '/new/img/path.jpg');
}, time);
Not tested but should work. I'll work on an example.
1 Comment
HAWKES08
basically i have 3 divs in a row. i need the background to change on each div in order every 10 seconds in a loop.
setInterval()