tags:

views:

35

answers:

4

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?

+1  A: 

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.

Nick Craver
i had to do the `position:absolute;` to deal with the jumping too :)
Moin Zaman
@Moin - That's not required really, that's a different problem, you're fading 2 at the same time *not* in the same queue, it's an entirely different approach.
Nick Craver
yup, that's intentional, I want to crossfade.
Moin Zaman
A: 

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/

Moin Zaman
A: 

I would hide, then change then show

$(function (){
    $('#container').hide(1000).html('New Text').show(1000)
})

you can use .fadeOut and .fadeIn instead of show and hide if you would prefer.

David Waters
`.html()` isn't a queued function, so this would change the text immediately, before the `.hide()` gets started even :)
Nick Craver
A: 

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);
Viktor Stískala