Rotating Text In Sequence with JavaScript and CSS3

Category: Animation , Javascript , Text | May 27, 2015
Author:rachsmith
Views Total:4,157 views
Official Page:Go to website
Last Update:May 27, 2015
License:MIT

Preview:

Rotating Text In Sequence with JavaScript and CSS3

Description:

A JavaScript and CSS based inline text rotator that enable you to loop thru words / terms of your sentence with fancy animations created using CSS3 transitions and transforms.

How to use it:

Insert a set of words / terms into your sentence.

<div class="text">
  <p>I Love</p>
  <p>
    <span class="word">JavaScript.</span>
    <span class="word">CSS / CSS3.</span>
    <span class="word">HTML5.</span>
    <span class="word">Linux.</span>
    <span class="word">OS X.</span>
  </p>
</div>

Basic styles for the text rotator.

.text {
  position: absolute;
  width: 450px;
  left: 50%;
  margin-left: -225px;
  height: 40px;
  top: 50%;
  margin-top: -20px;
}
p {
  display: inline-block;
  vertical-align: top;
  margin: 0;
}
.word {
  position: absolute;
  width: 220px;
  opacity: 0;
}

Create animations between words using CSS3 transitions and transforms.

.letter {
  display: inline-block;
  position: relative;
  float: left;
  transform: translateZ(25px);
  transform-origin: 50% 50% 25px;
}
.letter.out {
  transform: rotateX(90deg);
  transition: transform 0.32s cubic-bezier(0.55, 0.055, 0.675, 0.19);
}
.letter.behind { transform: rotateX(-90deg); }
.letter.in {
  transform: rotateX(0deg);
  transition: transform 0.38s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}

Start animate the text rotator.

var words = document.getElementsByClassName('word');
var wordArray = [];
var currentWord = 0;
words[currentWord].style.opacity = 1;
for (var i = 0; i < words.length; i++) {
  splitLetters(words[i]);
}
function changeWord() {
  var cw = wordArray[currentWord];
  var nw = currentWord == words.length-1 ? wordArray[0] : wordArray[currentWord+1];
  for (var i = 0; i < cw.length; i++) {
    animateLetterOut(cw, i);
  }
  
  for (var i = 0; i < nw.length; i++) {
    nw[i].className = 'letter behind';
    nw[0].parentElement.style.opacity = 1;
    animateLetterIn(nw, i);
  }
  
  currentWord = (currentWord == wordArray.length-1) ? 0 : currentWord+1;
}
function animateLetterOut(cw, i) {
  setTimeout(function() {
    cw[i].className = 'letter out';
  }, i*80);
}
function animateLetterIn(nw, i) {
  setTimeout(function() {
    nw[i].className = 'letter in';
  }, 340+(i*80));
}
function splitLetters(word) {
  var content = word.innerHTML;
  word.innerHTML = '';
  var letters = [];
  for (var i = 0; i < content.length; i++) {
    var letter = document.createElement('span');
    letter.className = 'letter';
    letter.innerHTML = content.charAt(i);
    word.appendChild(letter);
    letters.push(letter);
  }
  
  wordArray.push(letters);
}
changeWord();
setInterval(changeWord, 4000);

 

You Might Be Interested In:


Leave a Reply