JavaScript is causing a complete failure of CSS position transition functionality

Here are the tasks I want to accomplish:

  1. Show a div element;
  2. Move it to an initial position;
  3. Set transition properties;
  4. Move it to the target position using CSS transition.

Below is a minimal example:

function modifyElement() {
  /*  
    var obj = $('#box');
    obj.css("left", "200px");
    obj.css("display", "initial");
    obj.addClass("trans");
    obj.css("left", "500px");
  */

  var elem = document.getElementById('box');
  elem.style.left = "200px";
  elem.style.display = "initial";
  elem.className = "box trans";
  elem.style.left = "500px";
}
#btn {
  position: fixed;
  top: 60px;
  left: 0px;
  width: 50px;
  height: 50px;
  background-color: #FEDCBA;
}
.box {
  display: none;
  position: fixed;
  top: 0px;
  left: 0px;
  width: 50px;
  height: 50px;
  background-color: #ABCDEF;
}
.box.trans {
  -webkit-transition: left 2s;
  -moz-transition: left 2s;
  transition: left 2s;
}
<div id="box" class="box"></div>
<div id="btn" onclick="modifyElement()">Click Here</div>

JSFiddle Example.

The code is not functioning as expected. What could be the issue?

When I set the element to be initially visible, the transition starts smoothly from the origin left:0, even though I assigned elem.style.left = "200px"; before adding the transition properties...

Answer №1

Avoid incorporating style within your javascript code; instead, utilize class toggling and store animations in your CSS file.

Remember to avoid combining the transition property with display: none;; opt for using opacity: 0; as an alternative.

function example()
{
var item = $('#container');
item.toggleClass("effect");
}
#button
{
  position:fixed;
  top:60px;
  left:0px;
  width:50px;
  height:50px;
  background-color:#FEDCBA;
}

.container
{
  opacity: 0;
  position:fixed;
  top:0px;
  left:0px;
  width:50px;
  height:50px;
  background-color:#ABCDEF;
  -webkit-transition: transform  2s,opacity  2s;
  transition: transform  2s,opacity  2s;
}

.container.effect
{
  opacity: 1;
  -ms-transform: translate(500px,0); /* IE 9 */
  -webkit-transform: translate(500px,0); /* Safari */
  transform: translate(500px,0);

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container" class="container">
</div>
<div id="button" onclick="example()">
click here
</div>

Answer №2

Whenever DOM changes are made, they won't be visible until the rendering process takes place. JavaScript operates on a single thread, meaning that only one block of code can run at a time, and it runs on the same thread as the rendering cycle.

Due to this setup, the renderer is unable to kick in unless you allow it some time to analyze the new state of the DOM by delaying the execution of your JavaScript code (using setTimeout or requestAnimationFrame). So essentially, if you don't give the browser time to render, only the final value before the renderer examines the DOM will be relevant.

This response from a previous interrogation covers exceptions to this general rule.

Check out an updated rendition of your jsfidde here that leverages requestAnimationFrame to maneuver around this hindrance.

Answer №3

I am unable to provide a clear explanation for this phenomenon. It is a topic of curiosity for many, including myself. One theory suggests that implementing a time-out can help address the issue.

setTimeout(function(){
    elem.style.left = "500px";
},1);

It is possible that the rapid assignment of the property 'left' to 500 may be causing difficulties in accurately capturing the previous location at 200.

https://jsfiddle.net/UniqueUser/q4j23he8/7/

Answer №4

The reason for the delay is due to the hidden state of the div; it must first be displayed before the transition can take effect.

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

What methods can be utilized to avoid displaying a Bootstrap popover intermittently within an AngularJS framework?

When using the bootstrap popover in a custom AngularJS directive, I need to display an error message when the button is disabled by setting $scope.buytypeButton= {type:false}. The error message should be displayed in a popover. On the other hand, when $sco ...

Modify the date format inside the content of an HTML element or its descendants (excluding their attributes)

I have been trying to reformat some dates using JavaScript. My initial approach was: var regex = /(\d{4})-(\d{2})-(\d{2})/g; $('.container td').each(function() { $(this).html($(this).html().replace(regex, '$3-$2-$1')); ...

What is the alternative functionality of the "g" flag in the test method of RegExp?

http://jsfiddle.net/bpt33/ var t = ""; var a = ["atom-required","atom-label","atom-data-type","atom-regex"]; var r = /atom\-(label|required|regex|data\-type|class|is\-valid|field\-value|error)/i; function test(a, r){ for(var i = ...

The server mistakenly opened the index in the opposite direction

I am currently working on a React application that I launch from an Express server. Within my project, I have a public directory containing an index.html file, as well as a duplicate of that file in the root directory. Here is my code snippet: const exp ...

Display the flowplayer div when the anchor is clicked

I have a dynamic CGI page that displays a list of files. The number of files varies based on uploaded content, so I am looking to create previews for video files. Below is a snippet of HTML code: <TMPL_LOOP files> <tr> <td&g ...

The header bar intrudes into the main content area

I am in the process of transitioning my landing page design from Bootstrap to Semantic-UI. The layout includes a fixed top navbar and main content split into two columns (3-cols and 9-cols) - the left column is reserved for a sidebar, while the right colum ...

Enclose specific content items with double div elements using JavaScript every nth time

I have been attempting to encapsulate two divs around every set of three content pieces received from an API call. The desired structure is as follows: <div class="carousel-inner"> <div class="item carousel-item"> <div cla ...

I am puzzled as to why my ajax script is giving me a 404 error even though the URL appears to be correct

Even though it's not a cross-domain problem, Ajax is returning a 404 error code. In my TIZEN Web application project, I am trying to make an ajax request to a WebService that contains functions necessary for the project. Initially, the xhr.status was ...

Tips for updating the styleurls link dynamically by clicking a button and maintaining the changes

In the midst of developing an angular 2 project, I am currently working on integrating theme settings. Within my project, I have crafted three distinct component.scss files: red.component.scss, yellow.component.scss, and blue.component.scss. My goal is t ...

Struggling with the lack of two-way data binding functionality in Kendo UI

Recently, I encountered a challenge with my kendo-dropdownlist component. Initially, I was fetching data from an API using the kendo-datasource and everything was working smoothly. However, as I started to implement multiple instances of the kendo-dropdown ...

It appears that my array is not being properly populated by my callback functions

I am encountering an issue with my callback functions. The objective of my code is to send 16 GET requests to a REST API in order to retrieve 16 distinct JSON files. These JSON files are then supposed to be converted into dictionaries representing the foot ...

Exploring the Potential of Mobile Development using AngularJS

I am in the process of creating an app with the following key design objectives: Efficiency and modularity - a light core that can be expanded to create a feature-rich app in a cohesive manner Mobile focus - this app is primarily aimed at mobile platform ...

Using await outside of an async function is not allowed

When working with a rest api in node.js, I have implemented functionality to automatically resize any uploaded images that are too large. However, I am encountering an error when trying to call my await method. Here is the code snippet: ': await is o ...

Troubleshooting the inability to set percentage values in Bootstrap styling

My goal is to create a bar with thin bars, but my use of Bootstrap limits my control over sizes. <template> <div class="container-fluid mx-auto"> <div class="row"> <div class="square rounded-pill&qu ...

When attempting to send data to the ServiceStack RESTful service, an error message of 'Access is denied' was received

I created a RESTful service using ServiceStack to send data to a database. It worked perfectly when tested locally. However, after deploying it to a server and running the same jQuery $.ajax call code, I encountered an 'Access is denied' error. I ...

Exploring Angular 2 Application Testing: Tips for Interacting with HTML Elements

In my Angular 2 Frontend testing journey, I came across a blog post ( ) where the author utilized ng-test TestBed for core testing in Angular. While the example provided was helpful for basic understanding, it lacked details on how to manipulate Elements. ...

Error received when querying Firebase database: TypeError - object does not have a hasOwnProperty function

I have been attempting to access my Firebase database using the following code: const lastCrawl = admin .database() .ref('/crawls') .orderByChild("dateAdded") .limitToLast(1) .once('value') .then((snapshot) => { retu ...

JavaScript causing display issues with Unicode characters

convert.onclick = function() { for (var i = 0; i < before.value.length; i++) { after.value += "'" + before.value.charAt(i) + "', "; } } <textarea id="before" type="text" name="input" style="width:100%;">* ...

Adjust the transparency level when hovering in an R Shiny application

I have an absolute Panel in my R shiny app and I am attempting to adjust its opacity based on the mouseover action. The goal is to have the opacity at 1 when the cursor is on the panel, and 0.5 otherwise. However, the code I tried ended up making the pane ...

Passing a parameter to an AngularJS directive, which triggers the opening of an ngDialog, and subsequently updating the value to reflect changes in the root scope

Struggling with a persistent issue here; Essentially, I have a directive that triggers an ngDialog to open. This directive should be able to receive a variable from the root scope. The directive contains a click event that opens an ngDialog which then use ...