How to use JS / jQuery .animate({ function for animate elements from Last to First / Reverse Animation

My query is simple,

i have this text animation that is combo of multi <span></span> element in <p> </p> from all charactors of my var content string.

No i use this code to animate this Line:

var content = 'This is Example Line of Animation, This is Example Line of Animation,';

var ele = '<span>' + content.split('').join('</span><span>') + '</span>';

$(ele).hide().appendTo('p').each(function (i) {
    $(this).delay(40 * i).css({
        display: 'inline',
        opacity: 0,             
    }).animate({
        opacity: 1       
    }, 100);
});
#mainbg {
width: 500px;
height: 300px;
background: yellow;
 overflow: auto;
 font-size: 40px;
 font-family: Four C Gauri;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="mainbg">
<p></p>
</div>

Now my query is that i want to make it reverse animation, from Last <span></span> element to first <span></span> element.

i have tried some of this practice but it did not work: Like direction: 'reverse', and animation-direction: 'alternate', etc..

var content = 'This is Example Line of Animation, This is Example Line of Animation,';

var ele = '<span>' + content.split('').join('</span><span>') + '</span>';

$(ele).hide().appendTo('p').each(function (i) {
    $(this).delay(40 * i).css({
        display: 'inline',
        opacity: 0,             
    }).animate({
        opacity: 1,
         direction: 'reverse',
    }, 100);
});

Although when i chane Opacity : 1 to 0 then it’s result like this:

var content = 'This is Example Line of Animation, This is Example Line of Animation,';

var ele = '<span>' + content.split('').join('</span><span>') + '</span>';

$(ele).hide().appendTo('p').each(function (i) {
    $(this).delay(40 * i).css({
        display: 'inline',
        opacity: 1,             
    }).animate({
        opacity: 0       
    }, 100);
});
#mainbg {
width: 500px;
height: 300px;
background: yellow;
 overflow: auto;
 font-size: 40px;
 font-family: Four C Gauri;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="mainbg">
<p></p>
</div>

This is not reversing my animation i want animation from Last <span> to first <span> Hopw you understand see in this pic. Just Like reverse Typing vanish effect
enter image description here

Plz help me out how can i get this ?

>Solution :

You need to animate in reverse order.
first you need get the length of all the span element inside p like this

let _spanLength = $("p span").length;

then after this you need to loop animate like this

$("p span").eq(_spanLength - (i + 1)).delay(40 * i).css({
    display: 'inline',
    opacity: 0,             
}).animate({
    opacity: 1       
}, 100);

here is the working Demo

Leave a Reply