Search code examples
jqueryhtmlcssrotationtext-rotation

Rotating content in JQuery 1.11.0 - all DIVs appear on refresh


I've set up a sample page to make this rotator script work: http://twohatsconsulting.com/rotator/

The only problem is that when the page refreshes, all three DIVs appear before fading into the first DIV as it is intended.

My HTML code:

<div class="parent">
    <div class="child">
       first
    </div>
    <div class="child">
        second
    </div>
    <div class="child">
        third
    </div>
<div>

My JQuery code:

var currentItem = -1;
var direction = 1;

$(document).ready(function(){
    switchItem();
    setInterval(switchItem, 5000);  
});

function switchItem(){
    currentItem = (currentItem+1) % ($(".parent .child").size());
    // hide the visible one.
    $(".parent .child:visible").fadeOut(500, function() {
        //now that the hide is done, show the current one.
        $(".parent .child").eq(currentItem).fadeIn(500);
    });
}

Solution

  • The problem here is the first fadeOut takes 500 milliseconds. It's during this first half second that all elements are visible. Since you start with a currentItem of -1 you can use this to force the first change to happen immediately. For example:

    function switchItem(){
      var interval = currentItem == -1 ? 0 : 500;
      currentItem = (currentItem+1) % ($(".parent .child").size());
      // hide the visible one.
      $(".parent .child:visible").fadeOut(interval , function() {
          //now that the hide is done, show the current one.
          $(".parent .child").eq(currentItem).fadeIn(interval);
      });
    }
    

    Here's a fiddle to demonstrate how that would look