Randy
Randy

Reputation: 938

jQuery fadeOut: Fade out text, but keep surrounding text placement

I am using the standard fadeOut/fadeIn to replace text. But this text is being replaced in the middle of other text in my headings. Something like:

$('#flashable').fadeOut('slow', function(){
    $(this).delay(500);
    $(this).html(someNewText);
    $(this).fadeIn('slow);
});

When I do this, it works great, except that the DOM shifts to remove the previous text and then shifts back to put in someNewText. Is there any way that I can do this where that does not happen? It would look like this to the user

Originally:

The quick brown fox jumps over the lazy dog.

Fade out start:

The          brown fox jumps over the lazy dog.

Fade in ends:

The smart brown fox jumps over the lazy dog.

Note: the text I am replacing is always the same number of letters. So there shouldn't be flashes of DOM changes due to inserting someNewText that is a different length that what was previously in $('#flashable').html().

Upvotes: 3

Views: 5900

Answers (4)

Eric MJ
Eric MJ

Reputation: 738

could you show me you HTML structure?

well, do you wanna do this? http://jsfiddle.net/ericdum/AkJ9J/

$('#flashable').fadeTo('slow', 0, function(){
    $(this).delay(500);
    $(this).html("smart");
    $(this).fadeTo('slow', 1);
});

Upvotes: 2

jfriend00
jfriend00

Reputation: 707318

You can't use fadeOut() and fadeIn() because they hide the block of text when the animation completes which causes it to be removed from the page layout and things shift.

Instead, you can use fadeTo() which leaves the block of text in place and just changes it's opacity, but then you would also need to structure your HTML so that the two blocks of text were on top of one another.

Here's a working demo: http://jsfiddle.net/jfriend00/ahbyh/

Upvotes: 0

Arie Xiao
Arie Xiao

Reputation: 14082

You can replace fadeOut to fadeTo because fadeOut implies to set display: none; at the end of animation, which will cause the element box-model removed from the rendered page. However, fadeTo animates the opacity only and keeps the position and box-sizing of the element so the following elements will keep their original position:

$('#flashable').fadeTo(600, 0, function () {
    $(this).delay(600);
    $(this).html('smart');
    $(this).fadeTo(600, 1);
});

Example on jsFiddle

Upvotes: 6

Randy
Randy

Reputation: 938

And I just found this: jQuery text fade/transition from one text to another?

which uses animate/opacity. For other searchers, what I described above is called the "jumping" affect.

Upvotes: 0

Related Questions