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

Is there a way to focus on a specific iteration of the ngFor loop in Angular 9 using jQuery?

I'm working on a list of items inside a modal that uses *ngFor with checkboxes. The goal is to cross out the contents of an item when its checkbox is clicked. Here's the initial code using jQuery in home.component.ts: $('body').on(&apo ...

Issue: Unable to locate element with the specified selector: #email

const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://discord.com/register'); await page.screenshot({path: 'b.png ...

Issue with IE failing to load a particular Stylesheet

Have you had a chance to view this live demonstration? My website has two different stylesheets, one specifically for Internet Explorer and another for regular browsers. Here's how they are set up in the header: <link rel="stylesheet" type="text/c ...

Property usedJSHeapSize in Chrome

After doing some research online, I found that the documentation on this topic is quite lacking. I am currently dealing with a significant memory leak in my code and have been using: window.performance.memory.usedJSHeapSize However, it seems like the val ...

Convert JSON objects within an array into HTML format

Is there a way to reformat an array of JSON objects that has the following structure? [{"amount":3,"name":"Coca-Cola"},{"amount":3,"name":"Rib Eye"}] The desired output in plain HTML text would be: 3 - Coca-Cola 3 - Rib Eye What is the best approach to ...

Modify the CSS property of a checkbox label when the checkbox is selected

Recently, I came across some interesting HTML code: <label> <input type="checkbox" value="cb_val" name="cb_name"> my checkbox text </label> After applying CSS, I successfully added a background-color to the <label> t ...

Numerous points highlighted on the map

As I develop my application, I am working on setting up an event to automatically load data from a CSV excel file for display. My goal is to extract information from the Excel CSV file and use it to populate locations on a Google Map within my application ...

Executing JavaScript code from an external link

Currently, I am in the process of developing a horizontal parallax website. The functionality is working seamlessly; when I click on the menu, the slides smoothly transition horizontally and display the corresponding content. However, I have encountered a ...

Switching from a vertical to horizontal tab layout in Angular 4 Material 2 using MD-Gridlist

I'm currently trying to modify the tabbing functionality within an MD-Gridlist so that it tabs horizontally instead of vertically. I've experimented with tab indexes but haven't had any success. My goal is to enable horizontal tabbing throug ...

Issue with JavaScript not executing upon clicking the submit button on a form within the Wordpress admin page

In the admin pages of my Wordpress installation, I have created an HTML form. My goal is to validate the data inputted when the submit button is pressed using a Javascript function. If the data is not correctly inserted, I want alerts to be displayed. Desp ...

The error message stating that the specified CSS animation does not exist is triggered when using the cut-and-paste dropdown example

After trying Semantic 1.4.1 and also testing with 1.6.1, I copied the dropdown example directly from the documentation: <div class="ui selection dropdown"> <input type="hidden" name="gender"> <div class="default text">Gender</div& ...

Is there a way to access the original query string without it being automatically altered by the browser?

I'm currently encountering an issue with query strings. When I send an activation link via email, the link contains a query string including a user activation token. Here's an example of the link: http://localhost:3000/#/activation?activation_cod ...

Exploring HTML segments with Python and BeautifulSoup

As a beginner, I am exploring web scraping examples from Automate the Boring Stuff. My goal is to create a Python script that automates downloading images from PHD Comics using the following steps: Identify the image link in the HTML and download it. ...

Chrome Automatically Playing WebRTC Audio

My webapp has webrtc functionality, but I've noticed a strange issue. When connections are established between Chrome browsers, the audio is not played, while video is. However, this problem doesn't occur with Mozilla users. So... Chrome user 1 ...

Obtaining an element through its id using an expression in an Angular directive

Here's a complex question that needs to be broken down. I'm trying to mimic the behavior of the native <label> for <input>. Since nesting is not an option, I use a style like this: <input type="checkbox" id="test" /> Some other ...

Unexpectedly, Internet Explorer 11 is causing the "input" event to fire prematurely

While troubleshooting a JavaScript issue, I came across what seems to be a bug in Internet Explorer 11. I am reaching out here on StackOverflow for validation and to see if anyone else using IE11 can replicate this problem. The problem arises when the val ...

abandoning the upload of an item into a THREE.js environment

Currently, I am working on a THREE.js scene where I need to prevent uploading multiple files into the scene simultaneously. The setup involves using Angular to implement the three js scene and canvas as a factory to maintain only one instance of a canvas a ...

What could be causing the distance between the image and the navigation bar?

Hey there, I'm struggling with a pesky little gap that's sneaking in between an image and my navigation bar. I've exhausted all my usual tricks like setting inline-blocks on the ul and li levels, and trying to align everything left with text ...

Issues with PHP ajax causing database insertion failure

Here is the code for making an AJAX request: AJAX var date = new Date().toLocaleTimeString(); var text=this.value; var id=1; $.ajax({ type: "GET", url: "StoreMessages.php" , data: { room: id, msg:text, sendat:date } }); PHP Code if(isset($_GET['r ...

Using Vuex as a global event bus ensures that all subscribers will always receive notifications for

For a while now, I have relied on a global event bus in Vue - creating it as const bus = new Vue(). It works well, but managing subscriptions can get tedious at times. Imagine subscribing to an event in a component: mounted() { bus.$on('some.event ...