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

What steps can be taken to disable Angular's automatic trimming of fields?

Is there a global way to prevent Angular from automatically trimming input fields throughout the entire application? I know that I can avoid it for specific fields using the ngTrim directive, but it's not ideal to add this directive to every text fiel ...

What is the most effective way to reduce the number of http requests caused by onChange events in Material UI Slider?

Is there a way to optimize my request handling? In my React project, I am currently utilizing Material UI's slider. With the onChange property, I am making HTTP POST requests whenever the slider is moved. Here is a snippet of the code: <Slider ...

Tips on adjusting the size of a font icon using an inline element prior to the font being fully loaded

I'm facing an issue with embedding an icon font within text so that it wraps properly. Currently, the only way I can achieve this is by using &nbsp; between the text and the icon (i tag with font awesome). However, this causes a problem as the ico ...

Mixed Protocol Error (HTTP/HTTPS)

I'm experiencing a mixed content error on my website, as it is using both http and https protocols. Chrome console displays the following error: Mixed Content: The page at '' was loaded over HTTPS, but requested an insecure XMLHttpReques ...

Begin your meteor project with a remote MongoDB server on a Windows operating system

Currently tackling a project that requires me to integrate my meteor project with a remote MongoDB server on Windows. I successfully set the environment variable (MONGO_URL="DB LINK") from OSX using terminal commands, but I'm encountering difficulties ...

Conflict in the naming and scoping of IE7 and IE8

While reviewing some code, I encountered a problem in Internet Explorer 7 and 8. Despite the constructor executing properly when stepped through, upon returning I received an error stating "Object does not support this property or method." How frustrating! ...

Navigating the complexities of applying CSS exclusively to child grids within Kendo Angular may seem challenging at first

This image illustrates the grid layout I have created an angular UI using kendo that features a nested grid. I am trying to apply CSS specifically to the child grid without affecting the parent grid. However, no matter what CSS I write, it ends up being a ...

Difficulty with two-dimensional arrays in Angular and Typescript

I am currently stuck trying to assign values to a 2-dimensional object array in Angular/Typescript. I have noticed that the last assignment seems to override the previous ones, but I cannot pinpoint why this is happening. Could someone please review my cod ...

Having trouble with running `npm start` on a computer that has different versions of Node and

I have encountered an issue with running a React application on two different computers. One computer, a MacBook, is running the app without any problems, while the other, an Ubuntu 18.04 machine, is having trouble starting it. Here are the configurations ...

Tips for displaying personalized error messages from your REST API in a JavaScript client

I'm utilizing a Java REST API that has been generated using swagger. If the client is unauthorized, I am sending custom error messages in response. public Response collaborationCollabIdDelete(Integer collabId, SecurityContext securityContext, Str ...

Leverage Vue3's v-html feature without the need for additional wrapping tags by using script

Is it possible to use Vue's v-html directive within a Vue 3 <script setup> setup without needing an additional wrapping tag? I am looking to achieve something similar to the following: <script setup> const html = ref(`<pre></pre& ...

Assign a unique ID to each Angular Material checkbox

Presently, I am facing an issue: I am required to generate md-checkboxes from a Database. The implementation is successful using ng-repeat. However, I am encountering difficulties in fetching the data from these checkboxes. Each entry in the Database has ...

"Learn the art of refreshing data in AngularJS following the use of $emit event handling

I am in need of assistance with AngularJS. How can I re-initialize a variable in scope after using emit? Here is an example code snippet: $scope.uiConfig = {title: "example"}; $scope.$emit('myCustomCalendar', 'Data to send'); $scop ...

Limit the selected values to calculate a partial sum

Imagine two distinct classes called professor and student: professor.ts export class Professor { id: number name: string } student.ts import { Professor } from "./professor" export class Student { ...

I encountered an issue with the onclick event in JavaScript

I have been struggling with an issue for some time now and I just can't seem to figure out what I am doing wrong. Here's the problem - when I click on a link on my website, a calculator should pop up. Then, when I click the off button on the calc ...

Observing for form input in Nuxt.js

There is a form on my webpage, which includes the following elements: <div v-if="this.userdata.address == ''">Please enter your address</div> Your address <input type="text" v-model="userdata.address" ...

Having trouble setting the select value with JavaScript in the Selenium web driver

I am working on a web page that includes a cascaded dropdown feature. The data in the second dropdown appears to be generated via ajax based on the selection made in the first dropdown. Here is the code for the first select option: <select class="form- ...

Alter the value of a parameter within a script tag with JavaScript/jQuery

Looking to dynamically change a parameter value using JavaScript or jQuery. Here is an example URL: www.exampleurl.com/somepage?foo=test I have a function that can extract the value after the 'foo' parameter: function getParameterByName(name, ...

Tips on adding TypeScript annotations to an already existing global function

I'm contemplating enhancing an existing project by incorporating TypeScript type annotations. Struggling to supply an external declaration file for a straightforward example: app.ts: /// <reference path="types.d.ts"/> function welcome (person ...

The issue with the jQuery fadeIn and fadeOut functions is that the second part of the <h1> element is not properly displaying

I am attempting to create a fade-in effect for an <h1> element with the text first part of title followed by a delay, then fading in the second part of the title so it appears as first part of title second part of title. My attempts at solving this ...