Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Animate on change of .innerHTML or .text

I'm translating my site by dynamically changing the text on the website with jQuery like this:

<span id="mySpan">Something in English</span>

$('#mySpan').html("Something else in Spanish");

It works great but, due to changes in the length of the text, it's a hard transition, the new text just appears and parent element is resizing instantly.

Is there an easy way to animate/ease the transition during the change of text? Like Fadeing and/or resizing nicely?

I know it's possible with hidden elements, but because I have lot's of text, I don't want to load this if not needed.

Thanks!

like image 261
dynobo Avatar asked Oct 17 '14 16:10

dynobo


1 Answers

Well, if your span element has a parent, e.g.:

<div class="parent">
    <span id="mySpan">Something in English</span>
</div>

you could do it like this:

$('#mySpan').animate({'opacity': 0}, 400, function(){
        $(this).html('Something in Spanish').animate({'opacity': 1}, 400);    
    });

Basically, you animate child span's opacity to 0, 400 is transition time in ms. After that action is done, you do a callback function which replaces span's html with wanted text while it still has opacity: 0, and then you do backwards animation to opacity: 1.

Live example

like image 87
Davion Avatar answered Oct 16 '22 01:10

Davion