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

Is there a way to reverse the animation playback in Angular?

I am working on an animation that involves a box fading from its original color to yellow. However, I would like to achieve the opposite effect: when the page loads, I want the box to start off as yellow and then fade back to its original color. The challe ...

Mastering MochaUI: A Comprehensive Guide

Can anyone direct me to a comprehensive tutorial for MoachaUI? I have a strong understanding of CSS, basic knowledge of JavaScript, and experience with PHP. The MoachaUI user interface has caught my interest, but I'm struggling to find a suitable lear ...

The issue with Lodash isEqual arises from the constructor specified by Angular

Currently, I am utilizing Lodash _.isEqual for performing a deep comparison between a local JavaScript object and another JavaScript object fetched through angular $get. The initial code indicates that the objects are not the same: $get({...}, function ( ...

Using JavaScript to save a file with a data URL in Internet Explorer

Need help with file conversion on different browsers. I developed an app that converts files, and everything was working perfectly in Chrome. However, when it comes to IE (10/11/Edge), I'm facing some challenges: 1) The HTML5 download attribute does ...

What is the best way to dynamically hide a textbox in JSP based on the selection of a

On my JSP page, I have a textbox and a checkbox. I attempted to use jQuery and JavaScript to hide the textbox when the checkbox is checked, but it doesn't seem to be working. Below is the code snippet: <p class="contact"> <input id="check" n ...

What issues could potentially arise from utilizing the MIME type application/json?

I'm currently developing a web service that needs to return JSON data. After doing some research, I found recommendations to use application/json. However, I am concerned about potential issues this may cause. Will older browsers like IE6+, Firefox, ...

The jQuery method serializeArray does not include the values of HTML textareas and checkboxes

Hello, I'm looking to send data to the server from an HTML form. The server I'm using is CodeIgniter and I'm utilizing the AJAX method. Here's the HTML form: <div id="fileupload"> <form id="upload-media-form" class="uploa ...

What steps should I follow to utilize a JavaScript dependency following an NPM installation?

After successfully installing Fuse.js using npm, I am having trouble using the dependency in my JavaScript code. The website instructions suggest adding the following code to make it work: var books = [{ 'ISBN': 'A', 'title&ap ...

Overlay text on top of image with fading transparency when hovering over it

Is there a way to make the transparent layer that appears when hovering over an image on a card only cover the image itself and not extend onto the footer of the card? Currently, the image on the card covers most of it, and I want the hover overlay to beh ...

Enhance User Experience by Making Each Background Slideshow Image Clickable

I want to create a background image slideshow for my photography portfolio. Each image should fade in and link to its respective gallery. I also want the text box to fade with the images and link to the corresponding gallery. The challenge is adding the li ...

A Guide to Effectively Extracting Data from Second Level JSON Arrays with

Hi, I'm having difficulty fetching the two attributes under CategoryImage in the second level of the JSON array parsing. Can someone help me with this? Thank you. <script> $(document).ready(function() { var cat=""; ...

guide on adding a variable to the link_to path

In my attempt to incorporate a variable into the link_to function below: <%= link_to '<button type = "button">Players</button>' .html_safe, live_players_path(:Team => @tmf) %> Whenever I click on this link, it seems to ...

Multiple ngFor loops causing only the final item to be displayed in the inner loop

Can someone assist with my code where I loop through firebase RTDB reference to retrieve a list and then use those results in a subsequent firestore query? The console logs the correct data, but my code only displays the last item in the loop inside ngFor. ...

I successfully made a GET request using Postman, but encountered an issue when trying to do the same request through a

Currently, my objective is to send URL encoded parameters through a GET request using the fetch function. To achieve this, I am attempting to display the parameters via Express in the following manner: app.get('/api', function (req, res) { c ...

Tips for Updating HTML Table Content Dynamically Using JavaScript without jQuery

I am in the process of developing a web application that requires me to dynamically change the content of an HTML table based on user input, all without relying on jQuery or any other external libraries. Adding rows to the table is not an issue for me, but ...

The importance of manually loading extensions and utilizing Ajax effectively for renderPartial

Within my yii application, I have implemented Tabs and am loading content via ajax using renderPartial(). To prevent redundant script loading, I have set processOutput to false. As a result, I aim to manually load all necessary scripts once on the index pa ...

Exploring Javascript through Python using Selenium WebDriver

I am currently attempting to extract the advertisements from Ask.com, which are displayed within an iframe generated by a JavaScript script hosted by Google. Upon manually navigating and inspecting the source code, I can identify the specific element I&ap ...

What is the solution for fixing an error that says "There is no 'style' property on the 'Element' type"?

I'm struggling to fix an error in my JavaScript code. I created a script to display a tab indicator when a tab is clicked, but I keep getting the error message: "Property 'style' doesn't exist on type 'Element'". The tabs them ...

CSS: The enigma of :nth-child - what eludes my understanding?

I have 2 divs which are similar to 2 td's in a table. My goal is to have 2 red divs, followed by 2 blue divs and so on. However, my current code doesn't seem to be working. Can someone point out what I am missing: <style> .irow :nth-child( ...

Utilizing JavaScript text variables as hidden inputs

My JavaScript code is responsible for populating a modal from various sections of a website. Essentially, when the modal expansion button is clicked, it collects all data associated with that particular button press. While this functionality works flawles ...