Executing jQuery-controlled CSS animation in a synchronized manner

Is there a method to delay until CSS DOM changes take effect?

For instance:

CSS:

.box {
  width: 100px;
  height: 100px;
  background: red;
}

.anim {
    transition: transform 2s;
}

HTML:

<div class="box"></div>

jQuery:

$(".box").css("transform", "translate3d(200px,0,0)");
$(".box").addClass("anim");
$(".box").css("transform", "translate3d(210px,0,0)");

JSFiddle example: https://jsfiddle.net/tfxbej9q/

Expected behavior: <div> should instantly jump to position 200, then apply animation and smoothly move <div> 10px to the right (position 210).

Actual behavior: <div> is uniformly moved from position 0 to 210.

My current workaround involves using a setTimeout function:

 $(".box").css("transform", "translate3d(200px,0,0)");
 setTimeout(function() {
      $(".box").addClass("anim");
      $(".box").css("transform", "translate3d(210px,0,0)");
 }, 10);

Are there any functions that wait for DOM changes to be applied?

Answer №1

Dealing with a similar issue not long ago, I found a solution using window.requestAnimationFrame.

This issue isn't specifically related to jQuery; it's the browser's attempt to minimize repaints. To resolve it, you need to prompt the browser to perform 2 repaints either by incorporating a timeout/requestAnimationFrame/.delay(1) or triggering a restyling of the elements using something like offsetHeight.

$(".box").css("transform", "translate3d(200px,0,0)");
window.requestAnimationFrame(function(){
  $(".box").addClass("anim");
  $(".box").css("transform", "translate3d(210px,0,0)");
});

Your approach utilizing a timeout seems quite effective. Check out this jsfiddle example

$(".box").css("transform", "translate3d(200px,0,0)");
$(".box").get(0).offsetHeight;
$(".box").addClass("anim");
$(".box").css("transform", "translate3d(210px,0,0)");

Another jsfiddle example for reference

mgHenry created a handy jQuery extension to enhance the appearance of your code Find it here

Answer №2

One option is to utilize jQuery functions or methods that provide a complete callback feature, like the jQuery animate function.

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

Any ideas on what I might be doing incorrectly that's causing this div to not be perfectly centered? It seems a bit

I need help centering a div horizontally to a marker. I have been following this example here http://jsfiddle.net/rKejG/8/, but it seems to be slightly off to the right. Here is my code: $("#infobox").css({ marginLeft: (parseInt($("#content").width() ...

What is the best way to use a Handlebars file on multiple routes?

I have been working on extracting articles from a news website by scraping them successfully. The data is being displayed properly on the front-end console log, but I am facing an issue with rendering it onto the page using a button - it only appears when ...

Is it possible to integrate Google Analytics with Next.js version 13?

Is there anyone who has successfully integrated Google Analytics with NextJS 13? I tried following the steps outlined in this thread: How to implement Google Analytics with NextJS 13?, but despite doing everything as instructed, I am not seeing any data o ...

The website functions perfectly in Firefox, but encounters issues in Chrome

Having an issue with my website where a table is not displaying correctly next to an image in Chrome, even though it works fine in Firefox. Here is the CSS: #right{ float:right; position: absolute; } #left{ float:left; position: absolute; } This is how t ...

Troubleshooting: Navbar dropdown menu in AngularJS gets hidden within UI layout

After spending some time trying to understand why the NavBar drop-down is getting overlapped inside the ui-layout, I realize that I must be overlooking some basic steps. This issue seems so simple, yet it is eluding me. To see the details of the problem, ...

Is it possible to create multiple text input components using the "each" function, and how can I update the state by combining all of them together?

I am looking to create a text-based word game where the length of each word changes with every level. Each letter will be placed in its own box, forming a matrix (e.g. 10 words, length: 10 => 10x10 matrix). How can I generate multiple text input compone ...

Getting nested documents from an array in Meteor and MongoDB: A step-by-step guide

This is a continuation of my previous inquiry on this topic here on stackoverflow.com. Firstly, I want to express my gratitude to @David Weldon. With his guidance, I successfully organized my update. However, upon retrieving the data from the database, I ...

The function queryDatabases is not supported in the DocumentDB JavaScript API

Currently, I am developing a service for Azure Functions using JavaScript/Node.js. However, I encounter an error when trying to access the function DocumentClient.queryDatabases. Despite having the correct references installed in Visual Studio Code and bei ...

Navigate from Product Listing to Product Details Page by utilizing JSON data with ReactJS

I have successfully retrieved the initial level of JSON Data, which consists of objects/Product List. My objective is to implement a functionality where clicking on the "View Details" button will redirect to the respective product detail page, similar to ...

I'm looking to store a user's latitude and longitude in my postgres database by utilizing the HTML5 map. What steps do I need to take to accomplish

After the user clicks to save their position, we will store it in our longitude and latitude columns. Thank you for helping us with this task! Visit our Github repository here. Below is the excerpt from our HTML file where users can save their location c ...

Fill in the missing keys, values, and data within the JSON object

My JSON data consists of various objects with unique dates and site names. The dataset contains distinct dates such as: 2019-10-01, 2019-10-02, 2019-10-03, 2019-10-04, 2019-10-05. Some dates might be missing for certain sites in the dataset. For example, o ...

Can you notify all channels when the discord bot experiences a crash?

Is there a way to have my discord bot send a message in a specific channel when it crashes, similar to what I've seen with other bots? ...

Retain chosen option after form submission in PHP/HTML

I have seen many questions asked about this before, but despite trying various solutions here, none seem to work for me. I am populating a list from my mysqli database: <select multiple="multiple" name="formCountries[]" size="5" id="keuzeproduct"> ...

How can I iterate through elements in an array with the onClick event handler in React?

I have a set of data elements. const quotes = [ {"author": "Marilyn Monroe", "quote" : "I'm selfish, impatient and a little insecure. I make mistakes, I am out of control and at times hard to handle ...

Display or conceal a div element individually

My task involves modifying this code, which is the original version of a FAQ with three answers that can be toggled to show or hide on click. I need to revise it so that only one answer is displayed at a time and the others close. I received advice to us ...

Why is the MVC controller failing to produce JSON data?

When trying to return JSON data of a Product from a controller with the name JsonDetailsProduct, I encountered an issue. It seems that the success function of my Jquery call is not receiving any data, indicating a possible error within the controller. Her ...

Encountered an issue during the creation of a Nuxt.js project using the command line tool, where a SyntaxError was triggered

I encountered an issue while attempting to set up a nuxt.js starter project using the nuxt cli. Here are the steps I followed: Installed vue cli globally with the command: npm install -g vue-cli Created the project using: vue init nuxt-community/star ...

Retrieving data from an array of resolved Promises

I'm using axios.all to iterate through an array of items and send a GET request for each one in order to store their data correctly. Currently, I have an array of Promises that are all resolving with the right data, and the callback function triggers ...

Using Angular 2 to toggle visibility based on a select box's value

<div class="form-group"> <label class="col-md-4 control-label" for="is_present">Is Present?</label> <div class="col-md-4"> <select id="is_present" name="is_present" class="form-control" *ngIf="candidates.is_present === tr ...

How can jQuery validation be used to make fields required based on certain conditions?

Hey there! I'm using the awesome jQuery plugin that can be found at this link. In my form, I've added checkboxes that reveal additional fields to the user when selected. I want to make these fields required when the checkbox is clicked, and not ...