What causes the unexpected behavior of JQuery's .animate() function?

I am currently working on a project that involves creating a div element for the purpose of dragging and dropping files. My goal is to have the height of the div increase when a file is dragged into it, and decrease when the file is dragged out.

To achieve this functionality, I have implemented event listeners for the 'ondragover' and 'ondragleave' events, along with utilizing the .css() function to adjust the height of the div. While everything works as intended using the .css() function, I encountered unexpected behavior when attempting to use the .animate() function. When dragging over the div, the height increases as expected, but if the file is then dragged out without being dropped, the height does not decrease as desired.

Feel free to experiment below by dragging a file in and out of the div without actually dropping it:


            function enter_drop(){
                $("#box").animate({height: "300px"}, 500);
            }

            function leave_drop(){
                $("#box").animate({height: "100px"}, 500);
            }
        

            <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
            
            <div id="box" style="background:#98bf21;height:100px;width:100px;margin:6px;float:left" ondragover="enter_drop()" ondragleave="leave_drop()"></div>

            <img id="drag1" src="http://cdn.sstatic.net/Sites/stackoverflow/img/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="234253534f460e574c56404b0e4a404c4d63110d534d44">[email protected]</a>" draggable="true" style="float:left">
        

Answer №1

The ondragover event is triggered continuously while an element is dragged over a drop target.

When using jQuery's .animate() function, each callback is queued up. This means that when you trigger the ondragleave event, there may still be animations running in the background.

To stop and immediately execute any pending animations, you can use the .stop(true) method to clear the animation queue.

function enter_drop(e){
  $("#box").animate({height: "300px"},500);
}

function leave_drop(e){
  $("#box").stop(true).animate({height: "100px"},500);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<div id="box" style="background:#98bf21;height:100px;width:100px;margin:6px;" ondragover="enter_drop()" ondragleave="leave_drop()"></div>

<img id="drag1" src="http://cdn.sstatic.net/Sites/stackoverflow/img/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="99f8e9e9f5fcb4edf6ecfaf1b4f0faf6f7d9abb7e9f7fe">[protected]</a>" style="width:50px;height:50px;" draggable="true">

Answer №2

It has been noted that @Cue's response correctly identifies the root cause of the issue.

Nevertheless, resorting to .stop(true) in order to halt an excessively drawn-out animation queue is not the optimal resolution. A more effective strategy involves triggering your animation only once on ondragenter.

In reality, a combination of both methods works best:

  • Initiate enter_drop just once on ondragenter
  • and utilize .stop(true).animate(... on ondragleave, ensuring that if the initial animation is still ongoing when leaving, the element won't resume the enter animation but rather come to a standstill at its current height position before animating back towards 100.

function enter_drop(){
  $("#box").animate({height: 300},350);
}

function leave_drop(){
  $("#box").stop(true).animate({height: 100},350);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<div id="box" style="background:#98bf21;height:100px;width:100px;margin:6px;float:left" ondragenter="enter_drop()" ondragleave="leave_drop()"></div>

<img id="drag1" src="http://cdn.sstatic.net/Sites/stackoverflow/img/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d2b3a2a2beb7ffa6bda7b1baffbbb1bdbc92e0fca2bcb5">[email protected]</a>" draggable="true" style="width: 100px;">

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

Creating a clickable color-changing grid: A step-by-step guide

In a grid of size 12 by 12, each corner will be clickable, selecting a 6x3 cell area starting from the corner. The selected cells will change color upon clicking any of the 4 corners. After selecting one corner, the remaining cells (126 cells) will be che ...

What is the best way to retrieve a value from an asynchronous method in Node.js that is using promises and also calling another asynchronous method?

I have created two methods for verifying the availability of data in a database and storing the data. The methods are as follows: function IfUserExists(userId) { logger.info(`Checking If ${userId} exists`); return new Promise(resolve => { ...

Troubleshooting Problems with Ajax File Uploads

Welcome to My Unique HTML Form <center> <form enctype="multipart/form-data"> {{ csrf_field() }} <label class="fileContainer"> <input type="file" id="uploadFile" name="input_upload_file[]" multiple /&g ...

eliminate several digits past the decimal place

I thought this would be a simple task, but I'm completely stuck with the code I currently have! https://i.sstatic.net/Y36Cg.png render: (num) => { return <span><b>{num.toFixed(2)}</b>%</span>; // rounding to two de ...

Uploading Files with PhoneGap using Ajax

I have been attempting to execute this PhoneGap example for uploading images from a device to a server. // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // functi ...

Locate and swap out a specific string within a variable using jQuery

After much searching, I have yet to find a solution to what I thought would be a simple question. Using the .clone() method, I successfully copied a li element containing multiple form fields and inserted it at the beginning of the form. My challenge now ...

Fix the positioning of a div in BootStrap and CSS code

Hey there, I'm relatively new to CSS/Bootstrap and currently in the process of learning. I might need to incorporate some CSS into the "chat_funcs" div, but unsure about what code to input to achieve my desired outcome. The issue at hand: What I am ...

Utilizing JavaScript variables imported from an external library in Next.js: A Guide

I am currently working on a Next.js with Typescript website and I am in the process of adding advertisements. The ad provider has given me instructions to embed this JavaScript code on my site: <script src="//m.servedby-buysellads.com/monetization. ...

Align the subtext to the right and center it vertically within a Bootstrap dropdown menu item

Is there a way to vertically align small captions on the right side of a dropdown menu, next to each item's text? The issue is that in the example below, the numbers are not properly aligned. https://i.stack.imgur.com/NZigW.png The numbers 123 and 1 ...

The syntax for jQuery

While delving into the world of jQuery, I stumbled upon a code snippet that caught my attention. Although I am well versed in jQuery's basic selector syntax $('element'), I must admit that the $. syntax perplexes me. Take for instance the fo ...

What is the process for extracting an array from an object?

How can I retrieve an object from an array using Node.js? I have tried the code below, but it's returning the entire object. What I actually need is to only print the name, for example, just "sethu". Code: var sethu = [{ name:'sethu', ...

Configuration options for content division in a table cell

Please see the following fiddle which I have attempted: http://jsfiddle.net/9LdEc/ code: html: <div id="CorpDealerSearch"> <div class="row"> <div class="left"> Quarter To Date </div&g ...

What is the best way to add HTML formatted text into Outlook?

In my Emacs, I've generated this syntax-highlighted code snippet and now want to paste it into an Outlook email with rendered HTML (without the actual HTML code). <pre> <span style="color: #a020f0; background-color: gtk_selection_bg_color;"& ...

"Utilizing Javascript's Regex to selectively replace only the first character

Forgive me if this is a beginner question, but I'm really unsure about this. Is there a regex solution to replace a character that appears first in a string? For example: 12 13 14 15 51 41 31 21 All data where '1' is the first character s ...

Login should only be tried when the error code is 403

I have encountered an issue with checking if the API token is expired. The process involves making a GET call, and if a 403 error is received from the API, then re-login is required. This is what I tried: app.get = async (body) => { return new Pro ...

The straightforward hyperlink to a specific section within a webpage is not functioning as expected

Having trouble with my HTML navigation in Angular, can't pinpoint the issue. When I click on a navigation button, the URL changes from http://localhost:8018/#/WebDev to http://localhost:8018/#WebDev Something off in my code? <head> < ...

tips for replacing multiple route parameters in Angular using the replace function

I am facing an issue when trying to replace multiple parameters using the angular replace function. The problem is that the function only detects the first parameter. For example, if I have this route admin/management/{type}/card/{id}, and use the route.r ...

How can JavaScript be used to deactivate an HTML form element?

Within this form, there are two selection buttons that require client-side validation. The user must choose one of them, and once a selection is made, the other button should automatically be disabled. Below is the script I have implemented: <html> ...

I can't understand why this question continues to linger, I just want to remove it

Is there a valid reason for this question to persist? I'm considering removing it. ...

clear background with logo embossed

I have encountered an issue while trying to place my logo on a black background with transparency. Instead of the background being transparent, now my logo is also becoming transparent which was not my intention. Does anyone have any suggestions or ideas ...