Josue Espinosa - 1 year ago 99
HTML Question

# How to fade, animate and change text, word in title / sentence

I have a very simple website problem. I have a sentence in which one word fades out, and is replaced by another word in an array. However, since the words all vary in length, the sentence width abruptly changes and it looks choppy. How can I animate the width? I tried adding a transition to the container of the sentence in css but that didn't work. I applied the transition as

1.5s all linear
, so it should be animating the width as well as everything else whenever there is change. Any ideas?

JSFiddle

EDIT: Sorry if I was unclear, I only want to fade out the word, not the entire sentence. I'm trying to animate the width to fit the new word. I don't want to change/add any elements, just solve with the current tags in place. Also, the objects pulled from the array need to be random. Just trying to think of some creative scripting :)

$(function() { // DOM ready$("[data-words]").attr("data-words", function(i, d){
var $self =$(this),
$words = d.split("|"), tot =$words.length,
c      = 0;

// CREATE SPANS INSIDE SPAN
for(var i=0; i<tot; i++) $self.append($('<span/>',{text:$words[i]})); // COLLECT WORDS AND HIDE$words = $self.find("span").hide(); // ANIMATE AND LOOP (function loop(){$self.animate({ width: $words.eq( c ).width() });$words.stop().fadeOut().eq(c).fadeIn().delay(1000).show(0, loop);
c = ++c % tot;
}());

});

});
p{text-align: center;font-family: 'Open Sans Condensed', sans-serif;font-size: 2em;}
sup{font-size: 0.3em;}

/* WORDS SWAP */
[data-words]{
vertical-align: top;
}
[data-words] > span{
position: absolute;
color: chocolate;
}
<link href='http://fonts.googleapis.com/css?family=Open+Sans+Condensed:300' rel='stylesheet' type='text/css'>
<p> You ordered <span data-words="1|3|28"></span> <b>big</b><sup>&trade;</sup> <span data-words="salad|macs|chips"></span></p>