Multiple executions of jQuery animate API detected

I am aiming to create a unique image effect using jQuery's animate API. This effect involves swapping the image source, fading in/out, and applying a rotateY animation. However, there seems to be an issue where the animation triggers multiple times if the mouse cursor is dragged several times before the mouseenter animation finishes.

The provided code snippet:

$(document).ready(function() {

  $("img[data-alt-src]")
    .mouseenter(function() {
    var img = $(this);
    img.finish().animate({ opacity: '-=1.0', deg: '+=90' }, {
      duration: 250,
      step: function(now) {
        img.css({
          '-moz-transform': 'rotateY('+now+'deg)',
          '-webkit-transform': 'rotateY('+now+'deg)',
          '-o-transform': 'rotateY('+now+'deg)',
          '-ms-transform': 'rotateY('+now+'deg)',
          transform: 'rotateY('+now+'deg)'
        });
      },
      complete: function() {
        img.data('tmp-src', img.attr('src'));
        img.attr('src', img.data('alt-src'));
      }
    });
    // Additional animation logic
  })
    .mouseleave(function() {
    var img = $(this);
    img.finish().animate({ opacity: '-=1.0', deg: '+=90' }, {
      duration: 250,
      step: function(now) {
        img.css({
          '-moz-transform': 'rotateY('+now+'deg)',
          '-webkit-transform': 'rotateY('+now+'deg)',
          '-o-transform': 'rotateY('+now+'deg)',
          '-ms-transform': 'rotateY('+now+'deg)',
          transform: 'rotateY('+now+'deg)'
        });
      },
      complete: function() {
        img.attr('src', img.data('tmp-src'));
      }
    });
    // Additional animation logic
  });

});
img {
  width: 150px;
  height: 150px;
  margin-right: 1.5em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>

  <div style="position: relative; display: inline-block">
    <img
      src="http://mcenter.lazim.org/image/cache/catalog/demo/nikon_d300_1-270x270.jpg"
      data-alt-src="http://mcenter.lazim.org/image/cache/catalog/demo/nikon_d300_3-270x270.jpg"
      alt="">
    <img
      src="http://mcenter.lazim.org/image/cache/catalog/demo/nikon_d300_1-270x270.jpg"
      data-alt-src="http://mcenter.lazim.org/image/cache/catalog/demo/nikon_d300_3-270x270.jpg"
      alt="">
    <img
      src="http://mcenter.lazim.org/image/cache/catalog/demo/nikon_d300_1-270x270.jpg"
      data-alt-src="http://mcenter.lazim.org/image/cache/catalog/demo/nikon_d300_3-270x270.jpg"
      alt="">
    <img
      src="http://mcenter.lazim.org/image/cache/catalog/demo/nikon_d300_1-270x270.jpg"
      data-alt-src="http://mcenter.lazim.org/image/cache/catalog/demo/nikon_d300_3-270x270.jpg"
      alt="">
  </div>
  
</body>
</html>

Answer №1

$(function() {

  $("img[data-alt-src]").on('mouseenter', function(e) {
      e.stopPropagation();
      e.preventDefault();
      var img$ = $(e.currentTarget);
      if (img$.hasClass('opened')) {
        return false;
      } else {
        img$.addClass('opened');
      }
      img$.finish().animate({
        opacity: '-=1.0',
        deg: '+=90'
      }, {
        duration: 250,
        step: function(now) {
          img$.css({
            '-moz-transform': 'rotateY(' + now + 'deg)',
            '-webkit-transform': 'rotateY(' + now + 'deg)',
            '-o-transform': 'rotateY(' + now + 'deg)',
            '-ms-transform': 'rotateY(' + now + 'deg)',
            transform: 'rotateY(' + now + 'deg)'
          });
        },
        complete: function() {
          img$.data('tmp-src', img$.attr('src'));
          img$.attr('src', img$.data('alt-src'));
        }
      });
      img$.animate({
        opacity: '+=1.0',
        deg: '-=90'
      }, {
        duration: 250,
        step: function(now) {
          img$.css({
            '-moz-transform': 'rotateY(' + now + 'deg)',
            '-webkit-transform': 'rotateY(' + now + 'deg)',
            '-o-transform': 'rotateY(' + now + 'deg)',
            '-ms-transform': 'rotateY(' + now + 'deg)',
            transform: 'rotateY(' + now + 'deg)'
          });
        }
      });
    })
    .on('mouseleave', function(e) {
      e.stopPropagation();
      e.preventDefault();
      var img$ = $(e.currentTarget);
      img$.removeClass('opened')
      img$.finish().animate({
        opacity: '-=1.0',
        deg: '+=90'
      }, {
        duration: 250,
        step: function(now) {
          img$.css({
            '-moz-transform': 'rotateY(' + now + 'deg)',
            '-webkit-transform': 'rotateY(' + now + 'deg)',
            '-o-transform': 'rotateY(' + now + 'deg)',
            '-ms-transform': 'rotateY(' + now + 'deg)',
            transform: 'rotateY(' + now + 'deg)'
          });
        },
        complete: function() {
          img$.attr('src', img$.data('tmp-src'));
        }
      });
      img$.animate({
        opacity: '+=1.0',
        deg: '-=90'
      }, {
        duration: 250,
        step: function(now) {
          img$.css({
            '-moz-transform': 'rotateY(' + now + 'deg)',
            '-webkit-transform': 'rotateY(' + now + 'deg)',
            '-o-transform': 'rotateY(' + now + 'deg)',
            '-ms-transform': 'rotateY(' + now + 'deg)',
            transform: 'rotateY(' + now + 'deg)'
          });
        }
      });
    });

});
img {
  width: 150px;
  height: 150px;
  margin-right: 1.5em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>

  <div style="position: relative; display: inline-block">
    <img src="http://mcenter.lazim.org/image/cache/catalog/demo/nikon_d300_1-270x270.jpg" data-alt-src="http://mcenter.lazim.org/image/cache/catalog/demo/nikon_d300_3-270x270.jpg" alt="">
    <img src="http://mcenter.lazim.org/image/cache/catalog/demo/nikon_d300_1-270x270.jpg" data-alt-src="http://mcenter.lazim.org/image/cache/catalog/demo/nikon_d300_3-270x270.jpg" alt="">
    <img src="http://mcenter.lazim.org/image/cache/catalog/demo/nikon_d300_1-270x270.jpg" data-alt-src="http://mcenter.lazim.org/image/cache/catalog/demo/nikon_d300_3-270x270.jpg" alt="">
    <img src="http://mcenter.lazim.org/image/cache/catalog/demo/nikon_d300_1-270x270.jpg" data-alt-src="http://mcenter.lazim.org/image/cache/catalog/demo/nikon_d300_3-270x270.jpg" alt="">
  </div>

</body>

</html>

Explore this amazing code snippet!

Answer №2

You have activated the same event too frequently, causing the animation to appear glitchy. Here are a few suggestions:

  1. Try utilizing MouseOver/Mouseout events

  2. Consider using addClass/removeClass for managing CSS animations

  3. Ensure that one CSS animation finishes before initiating another ()

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

Using PHP to download a file

I have successfully uploaded a PDF file to a directory named 'documents' on my web server. Currently, I am populating a table with data from my database, and I want to create links in the forms column that directly link to the associated files w ...

Tips for presenting validation messages from the server on the client side using react-query

Hey there! I have set up the Express route for the signup API call, which is functioning correctly on the server-side. However, my goal is to show these validation messages in real-time as the user inputs their credentials on the React client side app.post ...

Send a form using Ajax technology

Let's start by taking a look at the code I have written: routes.php $router->resource('vips','formController'); formController.php (I am only sharing the relevant function) public function store(CreateVipRequest $request, Vi ...

Applying a gradient overlay to an image using CSS

Feeling a bit frustrated with this issue. I'm working on my Joomla website utilizing Phoca Gallery, and the code it generates includes the following: <img class="pg-image" src="/images/phocagallery/other/thumbs/phoca_thumb_m_something.jpg" alt="So ...

Alter the HTML tag once the text is encompassed within it

Can you configure your HTML code to display (B) when the text in (A) is wrapped? If it's not wrapped, then just display (A) (A) <div> <span>abcdefgabcdefgabcdefg</span> <span>abcdefgabcdefgabcdefg</span> ...

Arranging items in a vertical column using CSS based on the content

I am facing an issue with aligning the values in a column under each other without percentages using my own html code, css, and bootstrap classes: <div class="d-flex"> <p class="table-string">91.86</p> <span ...

I am attempting to display the Δ symbol on my website, however, it is not appearing on the webpage

In my attempt to display my company logo on the website, I encountered an issue where the Δ symbol is not appearing correctly in the browser. strong class="footer-logo">KyΔnsys</strong To address this problem, I have implemented unicode charset=" ...

attempting to showcase a set of 4 cards simultaneously within a single carousel interface

I've encountered an issue while trying to create a slider for my card component. Despite several attempts, I'm struggling to display them properly. Adjusting the width of Carousel inner from 100% to 25% resulted in an increased number of pages i ...

I am looking to implement validation using JQuery on a text box in ASP.NET that is required if checked and has a maximum value

After much searching, I finally found a solution using a pop-up message to indicate that a certain field is required. It's important for me to maintain consistency in the way these messages are displayed. I managed to implement a required field with ...

Tips for assigning array variables to elements in querySelectorAll [Pure JavaScript]

I need help with assigning values from an array to elements selected by the querySelectorAll function. I am trying to write code that will change the text to different values in the array when the browser width is below 768px, but I'm facing some chal ...

Vue keeps reloading the page twice

I've been facing challenges with writing Vue code. Currently, I am utilizing both Vue and Vuetify frameworks. There are A and B pages in the application. It works fine when navigating to either the A or B page individually. However, an issue arises ...

I prefer children to have their own unique style, instead of inheriting their parent's CSS

I currently have a project structured in the following way: There is an index page with a full layout Separate PHP files that are included in the index page Bootstrap is used in the index page, however, in some of the separate PHP files I also use jqgri ...

Attempting to implement a secondary level of dropdown menu using CSS

As I begin, I want to mention that I have thoroughly reviewed all the sub sub menu questions, but unfortunately, I couldn't find anything that aligns with the code I currently have in place. Any assistance will be greatly appreciated. My current task ...

Creating a dropdown menu using HTML and CSS

Looking for assistance with implementing a dropdown list in HTML/CSS, specifically in React? Check out this tutorial: Link However, after trying to incorporate and modify the code in your React project, nothing seems to work. It appears to be an issue rel ...

Prevent PHP script from running during an AJAX request

Here is a brief overview of how my small application functions: users are prompted to input a URL into a simple text field. Upon any changes made to the input, my script attempts to extract and showcase the first 10 images found on that particular webpage. ...

Counting JQuery Classes in an HTML Document

My task involves creating a dynamic HTML form that allows users to enter card values, which are then counted and styled accordingly. Each set of cards is contained within a <section> element. However, I encountered an issue with my jQuery code where ...

Is there a way for me to incorporate a JavaScript file from another JavaScript file in HTML, even if it's just one line below?

It seems that the issue of using a function or a variable from file1 in file2 is not working as expected: <head> <script src="file1.js"></script> <script src="file2.js"></script> </head> Since file2 ...

Select a random option from the dropdown menu

I have the following script: <script> function $(id) { return document.getElementById(id); } function getImage() { $('loader').src='/misc/images/loading.gif'; var url = "http://mouse ...

Extracting HTML Data in Point of Interest (POI)

When creating a spreadsheet report using POI, I often come across html content with various tags like <p>, <b/>, &nbsp;, etc. Is there a way to parse these html tags in POI? Are there any functions in POI that can handle html content? Here ...

unable to modify the content of a

I need assistance with a javascript function that dynamically creates panels using an ajax request. Once the request returns valid json data, I populate all the widgets as follows: function createAllWidgets() { var funcid = 'get_widget_info' ...