Tips for utilizing the .animate() method in JS/jQuery to create a reverse animation effect, moving elements from the last position to the

My question is straightforward,

I have created a text animation that consists of multiple <span></span> elements within a <p> </p> for each character in my variable content string.

Currently, I am using this code to animate the text:

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, I would like to achieve a reverse animation effect, starting from the last <span></span> element and going towards the first <span></span> element.

I have attempted various methods such as setting direction: 'reverse', and

animation-direction: 'alternate',
, but without success.

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 changing Opacity : 1 to 0 results in the following:

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>

The current method is not achieving the desired reverse animation effect that I want. I am looking for an animation from the last <span> element to the first <span> element, similar to a reverse typing vanish effect as shown in this image: [link to image]

Please assist me in implementing this reverse animation effect. Thank you!

Answer №1

To achieve the desired effect, you must animate in reverse order. Start by calculating the total number of span elements within the p element like this:

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

Next, loop through the animation process using the following code:

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

For a demonstration of this technique, check out the working example provided in this Demo

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Triggering the react state update function through an onClick event

Trying to grasp React through a tutorial, but I'm confused about why I need to create a new function to pass to an JSX onClick instead of using the one returned from a React useState call directly. The following code works because it uses the handleB ...

Navigate to the element and retrieve a null offset

Currently, I am attempting to retrieve an element's ID from a select box and then scroll to that specific element using the following code snippet: // move to services $(function () { $("select.jump").change(function() { var selected = $( ...

Is it possible to execute a function defined within an eval() function using setInterval()?

const evaluation = eval(document.getElementById("codearea").value); setInterval(evaluation, 10); I am seeking a way to access a function that is declared within the eval function, for example: setInterval(evaluation.examplefunc, 10) I attempted ...

How can ternary conditional operators be transformed into if statements?

When dealing with minified code like this, f&&!f.error?k.button.b==k.button.c.G?k.button.Q(b,e,f,c,d):k.button.b==k.button.c.o&&k.button.P(b,e,f,c,d):(console.error(f),f=f.error.message||chrome.i18n.getMessage("error_tooltip"),k.button.v(b ...

Checking your input in real-time with jQuery

My jQuery code is designed to validate email inputs as the user types: $('#email').keyup(function() { if (!isValidEmailAddress(email)) { $('#validate').removeClass(); } else { $('#validate').removeClas ...

Unable to stack DIVs in a vertical arrangement

I'm having trouble replicating the 2:1 layout shown in the image below. The issue I'm facing is with aligning the two photos on the right vertically so they match perfectly with the photo on the left. I attempted using flex but the vertical distr ...

Is there a method in React to execute an if statement based on the detection of changed props?

Within my current setup, I have a component that maintains an array of posts. This component receives a prop called sortBy, which instructs it to retrieve data sorted by either popular or new. On initialization, the component fetches the posts and stores t ...

Adding or removing a class on hover in Tailwind: The simple way!

Is there a way to change the class upon hovering an object using tailwind classes? <span className='group inline-block relative'> Hello <span className='hidden absolute -top-16 left-16 group-hover:inline-block'>&#45; ...

Ensuring number types are correctly input using jQuery

I am currently struggling with a complex issue related to jQuery validation on optional fields that are specified as type="number". The problem arises when users are able to input normal letters in the field, even though upon form submission the value is r ...

Tips for aligning divs in Zurb Foundation 3 framework

My design conundrum involves a 12 column row and trying to make a series of four div blocks stay in a row without stacking as the browser size decreases. Currently, the divs start to stack when the browser gets smaller. I have 4 divs that should be displa ...

Tips for adjusting the hover size in a navigation bar

I'm currently learning how to use bootstrap and I'm attempting to create a navbar that shrinks when scrolled down, and I also want the hover effect on the links to be full-height. I've tried multiple approaches but haven't been successf ...

Navigating between pages in ReactJS using Material UI can be made simple and efficient with the

While working on creating a drawer for my dashboard using material-Ui, I encountered an issue with navigating between pages Let me start by sharing my app.js file where the product route is defined: <Provider store={store}> <BrowserRouter> ...

There appears to be no alteration in the documentation, yet why is there a discrepancy in image scaling based on width between Bootstrap 4 and 5?

My picture is positioned in a grid column. When utilizing Bootstrap 4, the .title-image { width: 60%;} style works as intended. However, upon transitioning to BS 5, the image suddenly expands and protrudes. It appears that the width attribute is now align ...

Tips for changing date format within Ajax javascript code

I am working with a JavaScript AJAX code: success:function(res){ var _html=''; var json_data=$.parseJSON(res.posts); $.each(json_data,function (index,data) { _html+='<span class=&apo ...

Stop modal from opening if a specific element in the modal opener is clicked

I have some code that I'm working with: <div class="owl-item text-center col-lg-6 col-md-6 col-sm-12"> <div class="thumbnail-variant-5 cursor-pointer" data-toggle="modal" data-target=".pz-modal"> <div class="thumbnail-variant-5-i ...

How to emphasize a dataset in ChartJS stacked bar chart by hovering over the legend?

My Chart.js displays a horizontal stacked bar chart with legends corresponding to different classes. Here's a snippet (using dummy data, please ignore the random names): https://i.sstatic.net/XNTZZ.png The left labels represent users, while the legen ...

Save React code as a single HTML file

My current project involves creating one-page websites for a specific service that only accepts single inline HTML files. To make these webpages as modular as possible, I am utilizing React to create ready components. The challenge is exporting the final R ...

Transferring data packets via WebSocket

Imagine a scenario where you have a string consisting of ones and zeros, for example: "0101101" Now, the question arises - is there a way to transmit only these bits using the WebSocket.prototype.send method? The first step would be to convert these bit ...

Can a reducer be designed to accommodate varying states dynamically?

Welcome to my React Application for ages 16 and above, featuring Redux. Within my bookRoom.js file, I have a component called bookRoom which is responsible for rendering a single rectangle on the screen, symbolizing a room. You can see a sample render of ...

Is it possible to programmatically set focus on a DOM element using JavaScript or jQuery?

My code dynamically loads select boxes based on user selections. I have a specific instruction to select an option, which looks like this: //returns a string of <option>s by ID $('#subtopic_id').load('ajax.php?f=newSubtopic&am ...