15ongm 15ongm - 4 months ago 9
HTML Question

How to animate change in text value using jQuery?

What is happening



enter image description here

What I want



Instead of having an abrupt transition, I want the numbers to
fadeIn
for
300ms
. So when I click on a number, it fades into view on the
#Demo-Card
, and if I click another number, then it fades into view. I've been trying to use
animate()
but to no avail.

If anyone could help me with this, it would be greatly appreciated!

My Code



HTML

<div id="Demo-Pane" class="container">
<div id="Demo-Card">
<div class="problem-header">
<h3><span class="problem-number">11</span> <span class="problem-equation">Problem</span></h3>
</div>
...
</div>
</div>


jQuery

$(document).ready(function () {
...
$(".nav-pills").children("li").click(function(){
...
/*Change problem number on #Demo-Card*/
newProblemNumber = $(this).children("a").text();
$("#Demo-Card").children(".problem-header").find(".problem-number").text(newProblemNumber);
});
});


JSFiddle

Note



My question is not a duplicate because unlike that question, I only want to change the value of the text and then fade that in. In addition I do not want to use
fadeIn
or
fadeOut
, as @DaniP said, because I don't want to move the Problem text.

Answer

You can use the callback function() for animate this way:

Set opacity to 0 -- When finish change the text and animate again to 1

$("#Demo-Card").children(".problem-header").find(".problem-number").animate(
    {opacity:0},200,function(){
       $(this).text(newProblemNumber).animate({'opacity':1})
    });
});

Updated Fiddle

Comments