jQuery change background image to several divs at random intervals -
i have several divs displayed next each other on site, each different background image. have created script changes background images @ random time interval, however, script changes images @ same time....i want each 1 change randomly, totally independent of other....i'd them fade, timing key question here.
here script i'm working with.
jquery(window).load(function(){ var images = ['images/gallery/gallery2thumb.jpg','images/gallery/gallery3thumb.jpg','images/gallery/gallery4thumb.jpg','images/gallery/gallery5thumb.jpg','images/gallery/gallery6thumb.jpg','images/gallery/gallery7thumb.jpg','images/gallery/gallery8thumb.jpg','images/gallery/gallery9thumb.jpg',]; var = 0; var timeoutvar; function changebackground() { cleartimeout(timeoutvar); // sure run once @ time jquery('.hexagon-in2.change').css('background-image', function() { if (i >= images.length) { i=0; } return 'url(' + images[i++] + ')'; }); timeoutvar = settimeout(changebackground, ( 300+math.floor(math.random() * 1700) )); } changebackground(); }); also see jsfiddle http://jsfiddle.net/qwjfn/2/
how can each div change background image @ random time intervals independently?
check this:
var images = ['http://www.placekitten.com/250/300','http://www.placekitten.com/260/300','http://www.placekitten.com/260/310']; var = 0; var alldivs = []; function changebackground() { alldivs = $(".hexagon-in2").each(function(){ setbg($(this),1000); }); } function setbg(div, time){ var timevar; cleartimeout(timevar); if( div == undefined){ return; } div.css('background-image', function() { if (i >= images.length) { i=0; } return 'url(' + images[i++] + ')'; }); timevar = settimeout(settimer, time); } function getrandomint (min, max) { return math.floor(math.random() * (max - min + 1)) + min; } function settimer(){ var imageindex = getrandomint(0,alldivs.length); setbg($(alldivs[imageindex]),3000); } $(function(){ changebackground(); }); working fiddle here: http://jsfiddle.net/qwjfn/10/
Comments
Post a Comment