jquery – Rotating text with Javascript

jquery – Rotating text with Javascript

A simple example using jQuery
is by storing the desired looping / swapping words into the data-* attribute:

$([data-words]).attr(data-words, function(i, words) {

    var $self = $(this).text(),
        words = words.split(|),
        tot   = words.length,
        c     = 0; 

    for(var i=0; i<tot; i++) $self.append($(<span/>,{text:words[i]}));

    var $words = $self.find(span);

    (function loop(){
      $self.animate({ width: $words.eq( c ).width() });
      $words.stop().fadeOut().eq(c).fadeIn().delay(1000).show(0, loop);
      c = ++c % tot;
/* DATA-WORDS Loop/swap words in sentence */
[data-words] {
  vertical-align: top;
  position: static;
[data-words] > span {
  display: none;
  position: absolute;
  color: #0bf;
  This is <span data-words=some|an interesting|some longer>some</span> text

  Say <span data-words=hi|wow>hi</span> to <span data-words=Javascript|Stack Overflow>mom</span>

<script src=//code.jquery.com/jquery-3.1.0.js></script>
  • The | -delimited words will be converted to Array and finally to child <span> elements
  • Such span elements need to be absolutely positioned inside the parent span
  • jQuery will than init a recursive loop, calculate the next word width, and animating it (fade + width)

How about jQuerys animate() function?

You can trigger an animation for each word in the array. Heres an idea, you will have to figure out how populate the variables hasMoreWordsInTheArray and nextWordInTheArray:

function animateParagraphTag(word) {
    if(hasMoreWordsInTheArray) {
        //some special code to calculate the best width based on the words length (theNewWidthValue)
            { width: theNewWidthValue },

You will have to calculate the width based on the length of the words and place that within the parameters of the animation, then, once the p tag finishes the expansion/contraction accordingly, it will trigger the callback function, you can then move on to the next element (word) of the array.

jquery – Rotating text with Javascript

Leave a Reply

Your email address will not be published. Required fields are marked *