Animation failing to be queued properly

Here is a snippet of code that moves a heading icon back and forth when you hover over the heading:

jQuery('h1.heading').hover(
  function(){ 
    $icon = jQuery('.heading-icon', this);    
    if( ! $icon.is(':animated') ){
        $icon.animate({ "margin-left" : "+=7px" }, 200, function(){
          $icon.animate({ "margin-left" : "-=7px" }, 400, function(){ 
             $icon.css('margin-left','auto'); 
          } );
        } );
    }      
  },
  function(){} 
);

However, there's a bug where if you hover over the heading too quickly, it ends up in the wrong position. I've tried using onComplete functions and checking if it's animated, but it still doesn't work as expected.

I thought about resetting the position after the animation ends so that even if it bugs out, it would at least go back to the original position. This solution only partially works and the issue persists.

Any ideas on what could be causing this? Why does the shake effect from jQuery UI work better?

Note: It's okay if the animation runs a few more times, the main goal is to have it stay in the right position once all animations are complete.

Can anyone offer some guidance? :)

EDIT

I was able to replicate the problem on JSFiddle - http://jsfiddle.net/yhJst/
==> try hovering up and down quickly over the headings

EDIT2

The issue doesn't seem to occur when there is only one heading... http://jsfiddle.net/scZcB/3/

Answer №1

One issue arises in your callback function when using animate on the $icon variable. The problem occurs when hovering over another element, causing that variable to change for the new hovered element.

To resolve this, consider implementing either $(this) in the callback or utilizing natural queuing:

Natural Queuing

jQuery('h1.sc_blogger_title').on('mouseenter', function(){ 
    $icon = jQuery('.sc_title_bubble_icon', this);    
    if( ! $icon.is(':animated') ){
        $icon.animate({ "margin-left" : "+=7px" }, 200).animate({ "margin-left" : "-=7px" }, 400);
    }      
});

http://jsfiddle.net/yhJst/1/

$(this)

jQuery('h1.sc_blogger_title').on('mouseenter', function(){ 
    $icon = jQuery('.sc_title_bubble_icon', this);    
    if( ! $icon.is(':animated') ){
        $icon.animate({ "margin-left" : "+=7px" }, 200, function(){
            $(this).animate({ "margin-left" : "-=7px" }, 400);
        });
    }      
});

http://jsfiddle.net/yhJst/2/


Alternatively, utilize a local variable.

If you've noticed, the current variable is global. To fix this, simply add the keyword var.

jQuery('h1.sc_blogger_title').on('mouseenter', function(){ 
    var $icon = jQuery('.sc_title_bubble_icon', this);    
    if( ! $icon.is(':animated') ){
        $icon.animate({ "margin-left" : "+=7px" }, 200, function(){
            $icon.animate({ "margin-left" : "-=7px" }, 400, function(){ 
                $icon.css('margin-left','auto'); 
            } );
        } );
    }      
});

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 is the best way to display and conceal a loader in order to reveal additional posts?

How can I display a loader when the user clicks on the "load more posts" button, show it while the posts are loading, and hide it once the posts have been successfully loaded? Additionally, I want to show the loader again when the user clicks on the button ...

Add custom scripts to individual components within a Vue.js application

After extensive searching, I still can't seem to find a solution to my current issue. My focus is on a Vue project with vue-cli, where I need to inject various scripts into different pages (leveraging vue-router). Here are more specific details: Thi ...

`validate.js verifying the elements within an array`

One of the challenges I'm facing in my JavaScript project is dealing with objects that have two array properties included. As part of my development process, I've decided to utilize the resources provided by the validate.js library. To illustrat ...

Hovering over a class list will modify various element IDs

Is there a way to change the height of an element with id = "header_nav" when hovering over the class "header_nav" li element? Here is the HTML Code: <div class="header_nav" id="header_nav"> <ul id="header_nav_mainmenu"> & ...

Open the JSON file and showcase its contents using Angular

I am attempting to read a JSON file and populate a table with the values. I've experimented with this.http.get('./data/file.json') .map(response => response.json()) .subscribe(result => this.results =result, function(error) ...

AngularJS directive facing a callback problem

Having trouble with callbacks while calling a service function This is the function defined in registrationService function checkUserAccess(incentiveLevel, callback, displayRegistrationView) { var url = "..."; httpWrapperService. ...

Currently working on enhancing the responsiveness of the login form

I am encountering difficulties while trying to make the page responsive. I've checked my basic code, but something seems off. Could you please take a look at the plnkr link below and give me some feedback on where I might have gone wrong? Here's ...

No tests were located for execution. Despite our efforts, a cypress.json file was not found in the search

Having recently set up Cypress in my project, I encountered an issue while attempting to run it using npx cypress run. The error message displayed was: Could not find any tests to run. We searched for a cypress.json file in this directory but did not ...

creating sleek animations with Pixi.js for circular shapes

Is it possible to create smooth animations on circles or sprites similar to D3.js hits in Leaflet? https://drive.google.com/file/d/10d5L_zR-MyQf1H9CLDg1wKcvnPQd5mvW/view?usp=sharing While D3 works well with circles, the browser freezes. I am new to Pixi. ...

Is there a way to incorporate the image that was uploaded from the server onto an HTML page without using the file extension?

$('#userInfoPhoto').html(function () { return '<img src="../uploads/' + thisUserObject.profileimage + '" alt = "userphoto" style="width:250px; height:250px"/>' }); This script is essential for rendering images on th ...

Retrieve the audio file from the server endpoint and stream it within the Vue application

I am working on a listing module which includes an audio element for each row. I need to fetch mp3/wav files from an API and bind them correctly with the src attribute of the audio element. Below is my code snippet: JS methods:{ playa(recording_file) ...

Convert HTML templates into JavaScript on the client side using Angular framework along with Browserify, Babel, ES2015, and Gulp

Having trouble with my Browserify Angular configuration file, specifically when using require() to load HTML templates. I attempted to use stringify or browserify-ng-html2js in the transform() function, but it resulted in multiple transform calls in my gul ...

Comparing the efficiency of Jquery draggable with thousands of elements versus updating the elements continuously

Currently, I am developing an application that involves dragging an image using Jquery's draggable utility. The image is accompanied by several overlay divs containing various components positioned based on pixel locations, sometimes reaching into the ...

Ways to transmit information from a React application to a Node server

As a Nodejs beginner, I am using the rtsp-relay library for live streaming. Currently, it is working in the frontend when the URL is included in the server proxy object like this: rtsp://.....@..../Stream/Channel/10. However, I want users to be able to inp ...

There are two different ways to set a hyperlink in HTML. One method is by using the href attribute, where you provide the URL inside the quotation marks. The other

While browsing, I stumbled upon this interesting piece of JavaScript code: onClick="self.location.href='http://stackoverflow.com/'" I incorporated this code into my website, and it seems to have the same effect as using the href attribute. Sin ...

Styling Process Steps in CSS

Just starting out with CSS! I'm looking to replicate the Process Step design shown in the image. https://i.stack.imgur.com/Cq0jY.png Here's the code I've experimented with so far: .inline-div{ padding: 1rem; border: 0.04rem gray ...

When using `console.log`, the object is displayed correctly. However, an error occurs when

Here is the code I've been working on: function parseJSONData(jsonData){ var property, type, name, identifier, comment, content; for(property in jsonData){ switch(property){ case "type": type = jsonData[ ...

Utilize Bootstrap multiselect for extracting values from optgroups and options

Having a select element with optgroups and bonded values, the structure is as follows: <select id="example-dataprovider-optgroups" multiple="multiple"> <optgroup label="Lime No. 2" value="b3a2eff6-5351-4b0f-986 ...

What is the best way to transfer a multidimensional array from PHP to JavaScript?

Attempting to extract array value from a JSON string, I utilize the json_decode function in PHP. <?php $jsonContent=file_get_contents('http://megarkarsa.com/gpsjson.php'); $jsonDecoded=json_decode($jsonContent,true); foreach($jsonEncoded[&apo ...

Add a delay in jQuery so that when triggered by a click, the element fades out smoothly or instantaneously

Currently, I am working on creating a script for a notification popup. My goal is to have the popup fade out either after a certain number of seconds or when the user clicks on the message. While I have been successful in getting each effect to work indi ...