How to interrupt a JQuery animation and restart it from the middle?

Currently, I am tackling my first JQuery project and facing a challenge. As the user mouseleaves the .container, the animation does not reset but continues as if they are still within it. My goal is to have the animation revert in reverse if the user decides to exit the container midway through. How can I achieve this?

$( document ).ready(function() {
    $('#facial span').fadeOut(0);
    $('.container').mouseenter(function(){
        // When the mouse enters the .container, #facial slides to the center of .container.
        $('#facial').animate({right: '25%'})
        // After sliding to the center, #facial pauses for 500ms.      
                    .delay(500)
        // Following the delay, #facial expands its width to 100% of .container.
                    .animate({right: 0, width: '100%'});
        // Display the span link at the bottom as an H2 with center alignment.
        $('span').fadeIn(600);
    }); 


    $('.container').mouseleave(function(){
       // Mouse leaves .container, and span fades out gradually.
      // $('span').css('display','none'); 
       $('span').fadeOut(500);
       // Mouse leaves the .container, #facial shrinks its width to 50%.
       // #facial slides back to the right of .container.
       $('#facial').animate({right: 0, width: '50%'});

   }); 
});

Check out my Demo for a better understanding.

Answer №1

To cancel all current and queued animations, you can utilize jQuery's stop(true) method.

For a demonstration, check out this revised version on jsFiddle.

Answer №2

Consider utilizing .stop(true, true, true)

var $view = $('<a href="x">View</a>');

$( document ).ready(function() {
    $('#facial span').fadeOut(0);
    $('.container').mouseenter(function(){
        // Slide #facial to center of .container when mouse enters.
        $('#facial').animate({right: '25%'})
                    .delay(500)
                    .animate({right: 0, width: '100%'});
        // Show the span link at bottom as H2 with center alignment.
        $('span').fadeIn(600);
    }); 


    $('.container').mouseleave(function(){
       // Slowly fade out span when mouse leaves .container.
       $('span').stop(true, true, true).fadeOut(500);
       // Shrink #facial's width to 50% and slide back to right of .container.
       $('#facial').stop(true, true, true).animate({right: 0, width: '50%'});

   }); 
});

Check out this jsfiddle example here

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

Encountering an issue with a class component stating that "this.setState is not a function

I am currently learning React JS and encountered an error when calling my first API in React. I keep getting the message "Unhandled Rejection (TypeError): this.setState is not a function." I have been trying to troubleshoot this issue on my own but haven ...

Assigning multiple identifiers to a single element

Multiple posts have emphasized the importance of using an ID only once. But, I'm facing a situation where I need to pass 2 PHP variables to my JavaScript. I initially thought of using document.getElementById, but since IDs must be unique, this approa ...

The module '@algolia/cache-common' is missing and cannot be located

summary: code works locally but not in lambda. My AWS lambda function runs perfectly when tested locally, utilizing Algolia within a service in the server. Despite installing @algolia/cache-common, any call to the lambda results in a crash due to the erro ...

It is not possible to attach separate links to images in a JavaScript slider

I am struggling with linking individual images in a JavaScript slider for a client's website. The slider is fully functional and works well, but I can't seem to figure out how to link the images properly. When I remove items from <--ul class= ...

Save the value of a webpage element into a variable and utilize it across multiple JavaScript files in TestCafe

We are working in the insurance domain and have a specific scenario that we want to achieve using TestCafe: 1st step: Login into the application 2nd step: Create a claim and store the claim number in a global variable 3rd step: Use the globally declared c ...

Choose from the options provided to display the table on the screen

One of the challenges I am facing involves a table with two columns and a select option dropdown box. Each row in the table is associated with a color - green indicates good, red indicates bad, and so on. My goal is to have all values displayed when the pa ...

Implementing WordPress link pagination for displaying only the next and previous buttons

I'm new to WP and need some guidance. I want to display a list of images in a post, with the ability for users to click next and previous to cycle through them like separate pages. To split the post into multiple pages, I added this code: <!- ...

Having trouble with the babel-loader and its version compatibility, as well as not finding the babel-loader folder in the node_modules directory when

Here are the steps I've taken: I cloned the project from Github. Ran the command 'yarn' to start the project. Encountered an error after running the command 'yarn start'. Even after following the steps provided in the e ...

Is ES5 essentially the same as ES6 in terms of my lambda search?

After doing a search on an array using ES6, I am having trouble figuring out how to rewrite the code in ES5 due to restrictions with Cordova not allowing me to use lambda functions... $scope.Contact.title = $scope.doctitles[$scope.doctitles.findIndex(fu ...

"Exploring the magic of product galleries: A behind-the-scenes look at how websites create images

Have you ever wondered how this website creates the customization effect in its gallery? When you adjust the color, stones, or other attributes of the ring, it appears as though a new image is being generated. (click Customize) Do you believe they have a ...

"Troubleshooting: Jquery Draggable Function Fails to Execute

I'm currently working on a JSP page where I am attempting to make the rows of a table draggable. Despite multiple attempts and combinations, I have been unable to make any elements draggable. The rows are appended after an AJAX call, but still no succ ...

Internet Explorer causing trouble with reliable Ajax dropdown selection

There are two drop-down lists on my website, where the options in one depend on the selection in the other. The Ajax code works perfectly fine in Chrome and Mozilla, but it's not functioning correctly in Internet Explorer (specifically IE9). I need so ...

Bundling sub-components using Rollup for NodeJS application packaging

My ES6 library consists of several sub-modules arranged like this: - package.json - lib - my_package - file1.js - file2.js - sub_module1 - file3.js - file4.js Currently, I import modules within my package using file resolution r ...

Using jQuery Datatables fnReloadAjax successfully triggers a reload of the data, however, it

In my jQuery datatable, I am utilizing the code below to refresh the data: $(".unread-rows").click( function(e) { e.preventDefault(); message_table.fnReloadAjax("/letters/ajax/inbox/1"); message_table.fnDraw(); $(this).addClass("active").s ...

Why is my npm installation generating an ERESOLVE error specifically linked to karma-jasmine-html-reporter?

Could someone help me understand this dependency error I encountered while running npm install and provide guidance on how to resolve such errors? View Error Screenshot I am currently using Angular 16, the latest stable version. npm ERR! code ERESOLVE ...

Retrieval of each single row from a PHP-generated JSON dataset

This is quite challenging, especially for me. My goal here is to use Javascript to extract each value of every row in this JSON data: {"id":2,"url":"image.png","x":19,"y":10,"user_id":20} {"id":3,"url":"image.png","x":19,"y":10,"user_id":20} {"id":4,"url" ...

Spotting the Visible Element; Detecting the Element in

Currently, my webpage has a fixed header and I am facing the challenge of dynamically changing the styling of the li elements within the navigation based on the user's scrolling position. To achieve this, I believe the most effective approach would b ...

Is it possible to submit a form using AJAX in WordPress without relying on WordPress functions?

As I work on constructing a website using Wordpress, I am encountering an issue with submitting a form via ajax. I'm wondering if it's possible to achieve this without relying on Wordpress functions. Currently, my code runs without errors and dis ...

What are the different ways to customize the indicator color of React Material UI Tabs using hex

Just got my hands on this amazing Material UI component <Tabs textColor="primary" indicatorColor="primary" > <Tab label="All Issues"/> </Tabs> The documentation states that indicatorColor and textColor can only be set to ' ...

Form validation on the client side: A way to halt form submission

I have a form with several textboxes. The unobtrusive jquery validation is functioning properly and correctly turns the boxes red when invalid values are entered. However, I've noticed that when I click to submit the form, it gets posted back to the s ...