Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery text fade/transition from one text to another?

Tags:

jquery

jQuery can obviously fadeIn/fadeOut text easily. But what if you want to change the text from one thing to another? Can this happen with a transition?

Example:

<div id='container'>Hello</div>

Can one change the text Hello to World but have it change with a transition (like a fade or some effect) instead of changing instantly?

like image 587
Jake Wilson Avatar asked Sep 08 '10 17:09

Jake Wilson


4 Answers

You can use callbacks, like this:

$("#container").fadeOut(function() {
  $(this).text("World").fadeIn();
});

You can give it a try here, or because of how the queue works in this particular case, like this:

$("#container").fadeOut(function() {
  $(this).text("World")
}).fadeIn();

This executes the .text() call when the .fadeOut() is complete, just before fading in again.

like image 146
Nick Craver Avatar answered Nov 13 '22 03:11

Nick Craver


If you'll use hide/show or fadeIn/fadeOut you may encounter some "jumping" effect, because it changes CSS display property. I would suggest using animate with opacity.

Like this:

$('#container').animate({'opacity': 0}, 1000, function () {
    $(this).text('new text');
}).animate({'opacity': 1}, 1000);
like image 21
Viktor Stískala Avatar answered Nov 13 '22 04:11

Viktor Stískala


Here is a live example.

(function() {

var quotes = $(".quotes");
var quoteIndex = -1;

function showNextQuote() {
    ++quoteIndex;
    quotes.eq(quoteIndex % quotes.length)
        .fadeIn(2000)
        .delay(2000)
        .fadeOut(2000, showNextQuote);
}

showNextQuote();

})();

It works well.

like image 26
Bogdan Avatar answered Nov 13 '22 04:11

Bogdan


one way I can think of to do this is to have child elements with text and show only one to begin with, then fade the other ones in one after another.

have a look here: http://jsfiddle.net/VU4CQ/

like image 4
Moin Zaman Avatar answered Nov 13 '22 03:11

Moin Zaman