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;
}
<p>
This is <span data-words="some|an interesting|some longer">some</span> text
</p>
<p>
Say <span data-words="hi|wow">hi</span> to <span data-words="Javascript|Stack Overflow">mom</span>
</p>
<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 parentspan
- jQuery will than init a recursive loop, calculate the next word width, and animating it (fade + width)