Daren Smit Daren Smit - 2 months ago 12
CSS Question

How do i fade in/out a number of divs randomly every 5 seconds

I have a problem with my code that i can't figure out. I want to show 4 divs that change every 5 seconds but somehow my function won't change every 5 seconds but every 1 second or so.

Html Code:

<div class="Image"><img src="image1.jpg">1</div>
<div class="Image"><img src="image2.jpg">2</div>
<div class="Image"><img src="image3.jpg">3</div>
<div class="Image"><img src="image4.jpg">4</div>
<div class="Image"><img src="image5.jpg">5</div>
<div class="Image"><img src="image6.jpg">6</div>
<div class="Image"><img src="image7.jpg">7</div>


CSS Code:

div.Image {
display: none;
}


Jquery Code:

$(document).ready(function(){
var divs = getRandomDivs();

fadeTheDivs(divs);
});

function getRandomDivs()
{
return $("div.Image").get().sort(function(){
return Math.round(Math.random())-0.5; //random so we get the right +/- combo
}).slice(0,4);
}

function fadeTheDivs(divs)
{
setTimeout(function(){
$(divs).fadeToggle("slow","", function(){
var divs = getRandomDivs();

fadeTheDivs(divs);

});
}, 5000);


Can someone please help me?
JSFiddle: http://jsfiddle.net/FyzXF/113/

Answer

Here is a solution using another tools like promise() and delay() no setTimeOut. Check this:

$(document).ready(function(){
  var divs = getRandomDivs();
  fadeTheDivs(divs);
});

function getRandomDivs()
{
  return $("div.Image").get().sort(function(){ 
    return Math.round(Math.random())-0.5;
  }).slice(0,4);
}

function fadeTheDivs(divs)
{
  $(divs).fadeIn('slow').delay(3000).fadeOut('slow').promise().done(function(){
   	var divs = getRandomDivs();
  	fadeTheDivs(divs);
  })
}
div.Image {
  display: none;
  width:50px;
  height:50px;
  background:tomato;
  margin:2px;
  color:white;
  line-height:50px;
  text-align:center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="Image">1</div>
<div class="Image">2</div>
<div class="Image">3</div>
<div class="Image">4</div>
<div class="Image">5</div>
<div class="Image">6</div>
<div class="Image">7</div>

Comments