Infinite Text Rotator with Vanilla JS and CSS3 – Word Cycle

Category: Animation , Javascript , Text | April 17, 2015
Author: jicub
Views Total: 3,815
Official Page: Go to website
Last Update: April 17, 2015
License: MIT

Preview:

Infinite Text Rotator with Vanilla JS and CSS3 – Word Cycle

Description:

Word Cycle is a vanilla JavaScript library to cycle through an array of words with a CSS3 powered fadeIn animation.

How to use it:

Wrap the initial word in an inline element.

<h1> I love <span class="verb">JavaScript</span>.</h1>

Add the necessary classList.js JS library at the bottom of the document.

<script src="js/classListShim.js"></script>

The core JavaScript to enable the text rotator.

var words = (function(){
  var words = [
      'JavaScript',
      'CSS3',
      'HTML5',
      'Ruby',
      'Python',
      'C++',
      'jQuery',
      'Google',
      'Object C',
      'Mysql'
      ],
    el = document.querySelector('.verb'),
    currentIndex,
    currentWord,
    prevWord,
    duration = 4000;

  var _getIndex = function(max, min){
    currentIndex = Math.floor(Math.random() * (max - min + 1)) + min;

    //Generates a random number between beginning and end of words array
    return currentIndex;
  };

  var _getWord = function(index){
    currentWord = words[index];

    return currentWord;
  };

  var _clear = function() {

    setTimeout(function(){
      el.className = 'verb';
    }, duration/4);
  };

  var _toggleWord = function(duration){
    setInterval(function(){
      //Stores value of previous word
      prevWord = currentWord;

      //Generate new current word
      currentWord = words[_getIndex(words.length-1, 0)];

      //Generate new word if prev matches current
      if(prevWord === currentWord){

        currentWord = words[_getIndex(words.length-1, 0)];
      }

      //Swap new value
      el.innerHTML = currentWord;

      //Clear class styles
      _clear();

      //Fade in word
      el.classList.add(
        'js-block',
        'js-fade-in-verb'
        );

    }, duration);
  };

  var _init = function(){
    _toggleWord(duration);
  };

  //Public API
  return {
    init : function(){
      _init();
    }
  };
})();

words.init();

Add the fadeIn animation to the text rotator using CSS/CSS3.

@-moz-keyframes 
fade-it { 0% {
opacity:0
}
100% {
opacity:1
}
}

@-webkit-keyframes 
fade-it { 0% {
opacity:0
}
100% {
opacity:1
}
}

@keyframes 
fade-it { 0% {
opacity:0
}
100% {
opacity:1
}
}

.js-fade-in-verb {
  animation-name: fade-it;
  animation-duration: 1s;
  animation-fill-mode: forwards;
  -webkit-animation-name: fade-it;
  -webkit-animation-duration: 1s;
  -webkit-animation-fill-mode: forwards
}

.verb.js-block { display: inline-block }

.verb.js-hide {
  display: none;
  opacity: 0
}

.verb {
  display: inline-block;
  visibility: visible;
  border-bottom: 1px solid
}

You Might Be Interested In:


Leave a Reply