Eric Guo Eric Guo - 1 month ago 10
jQuery Question

Quicker way to animate each word of a sentence?

I think I may need some help with CSS or Jquery, whichever one is more efficient with the least amount of code. Basically I want to change each word of a sentence to a different color one after the other. So lets say a sentence has 5 words. The first word turns red then back to black and then the second word turns red after the first word has reverted back to its original color and then on and on in an infinite loop going back to the first word. I cant figure it out so any help would be awesome. Thanks!

So far I have this:



.element1 {
animation: pulse 1s infinite;
animation-delay: 1s;
}
.element2 {
animation: pulse 1s infinite;
animation-delay: 1s;
}
.element3 {
animation: pulse 1s infinite;
animation-delay: 1s;
}
.element4 {
animation: pulse 1s infinite;
animation-delay: 1s;
}
.element5 {
animation: pulse 1s infinite;
animation-delay: 1s;
}
.element6 {
animation: pulse 1s infinite;
animation-delay: 1s;
}

@keyframes pulse {
0% {
color: black;
}
100% {
color: red;
}
}





and then the HTML I was thinking of wrapping each word into with a span tag.

Answer

Though, the question is not very clear, but here is my attempt to give you initials, as per my understanding.

var sentence = $('div#content').text();

var words = sentence.split(' ');

var spanWords = [];

$(words).each(function(i,word){ 
  if($.trim(word).length)
     {
       var span = $('<span>');
       span.text(word);
       spanWords.push(span)
       spanWords.push('&nbsp;')
     }
});

$('div#content').html(spanWords)

var start = function(element){
  if(element.next().length){
      setTimeout(function(){
      element.css({color: "#000"});
      start(element.next())
     },1000);
    }
  element.css({color: "#f00"});
}

start($('div#content span:eq(0)'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id='content'>
  Hello world. you are beautiful.
  </div>

Comments