Tiggles ツ of Speak Creative
2/4/2019 - 1:59 PM

Active element rotator

Script to cycle an 'active' class to a set of elements. good for carousels

$("#word-carousel .word-wrapper").each(function() {
  var $wrapper = $(this);
  $wrapper.find(".word").first().addClass("active");
  
  function changeActive() {
    var theWords = $wrapper.find(".word");
    var theFirst = $wrapper.find(".word").first();
    var theLast = $wrapper.find(".word").last();
    
    var theActiveOne = $wrapper.find(".word.active");
    var theNextOne = theActiveOne.next(".word");
    if (theActiveOne[0] === theLast[0]) {
      // no nexts - starting over
      theFirst.addClass("active");
      theActiveOne.removeClass("active");
    } else {
      // there is a next one
      theNextOne.addClass("active");
      theActiveOne.removeClass("active");
    } 

    setTimeout(changeActive, 5000);
  }

  changeActive();
});