I'm experiencing some unexpected behavior in JavaScript when I try to apply style changes using JavaScript. Is it possible that transitions are not occurring in both cases as expected?

Everything seems to be working fine with the transition, but when I skip using setTimeout and directly apply the transform, the div instantly reaches the end of the transition.

function move(x, y, delay) {
  let el = document.getElementById('myDiv');
  el.style.transform = `translateX(${x}%)`
  el.style.transition = `transform ${delay}s linear`

  setTimeout(() => {
    el.style.transform = `translateX(${y}%)`
  }, 1000)
}


move(100, 200, 1)
.myDiv {
  height: 50px;
  width: 50px;
  background: blue;
}
<div class="myDiv" id="myDiv">
  Content
</div>

In this scenario, the div immediately reaches the end of the transition. Since JavaScript is synchronous, shouldn't all these instructions be executed sequentially? Why isn't the entire transition taking place in this case?

function move(x, y, delay) {
  let el = document.getElementById('myDiv');
  el.style.transform = `translateX(${x}%)`
  el.style.transition = `transform ${delay}s linear`
  el.style.transform = `translateX(${y}%)`
}


move(100, 200, 1)
.myDiv {
  height: 50px;
  width: 50px;
  background: blue;
}
<div class="myDiv" id="myDiv">
  Content
</div>

Answer №1

It still seems a bit strange to me, but it's necessary to "refresh" the CSS changes. In order to do so, you have to access an element's property, such as el.innerText, before applying your new style.

 function move(x,y,delay){
    let el = document.getElementById('myDiv');
    el.style.transform = `translateX(${x}%)`
    el.style.transition = `transform ${delay}s linear`
    el.innerText;
    el.style.transform = `translateX(${y}%)`    
}

move(100,200,1)
 .myDiv{
      height: 50px;
      width: 50px;
      background: blue;
 }
<div class="myDiv" id="myDiv">
  Content
</div>

I'm uncertain about the cause of this issue, perhaps someone here could provide an explanation.

Answer №2

To achieve a sliding effect using CSS keyframes, you can implement the following code:

#myDiv{
animation: slidein 1s forwards

}
@keyframes slidein {
  from {
   transform: translateX(100%);
  }

  to {
    transform: translateX(200%);
  }
}
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style>
    .myDiv{
      height: 50px;
      width: 50px;
      background: blue;
    }
</style>
</head>
<body>

  <div class="myDiv" id="myDiv">
  Content
  </div>
    
</body>
</html>

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 tabs within a Dialog prevents the Dialog from adjusting its height automatically

Solved: Find the solution in the comments section below. I recently built a Tabs feature within a Dialog box, but ran into an issue where the height of the Dialog did not match up with the height of the tab. The problem arose when a form was placed insid ...

Utilizing Jquery for toggling HTML elements and styling with CSS

I'm trying to implement a jQuery toggle button that switches between two states below; When I click the Toggle Button/link, everything in picture A (above the red line) should be hidden. Clicking the toggle button again would make it reappear. I&apo ...

Steps for sending a form with jQuery's submit method1. Start

Below is the jquery code that I have written: $(document).ready(function () { $('.bar_dropdown').on('change', function() { console.log("dropdown changed") $('#bar_graph_form_id').submit(function(e ...

Unit Testing Angular: Mastering Unit Testing for the .map() Function

I am in need of testing a service method, but I am unsure about how to achieve complete coverage for the code that gets executed as a result of calling another injected service method. The Service Method to be tested: @Injectable() export class BomRevisi ...

Unlocking the secrets: Viewing encrypted HTML code in C#

I am facing an issue with my application that utilizes HttpWebRequest and HttpWebResponse to retrieve the HTML content of a page. The information I need is located within a Div, but when I extract it using the application, the Div appears empty without any ...

Absolute positioned TD creates a gap upon being displayed

Hey there, I am facing an issue with a table I have. In each row (TR), the last TD element has a class called 'abs'. The style for this class is specified in the provided code snippet. Initially, this element is hidden. However, when you hover o ...

How can I implement a dynamic sidebar drawer in Bootstrap for my navbar?

Is it possible to achieve a layout similar to this example: I've come across some online examples using different versions of bootstrap, but they tend to alter the css too much, making it harder to grasp the concepts of bootstrap. I am curious if it ...

Function that is triggered by scrollbar height indicator

I'm currently utilizing jQuery to retrieve the user's current height and triggering an animation function once they reach that height (similar to reactive websites where animations occur as the user scrolls down the page). However, I am struggli ...

Detaching jQuery event listeners

Suppose I have two event handlers of the same type attached to the same object. The following example shows the mousemove event being attached to the window object. $('body').on('mousedown', '#uiScrollbar', function(e) { v ...

Using JQuery and Ajax, what is the best way to transfer information from a popup form to a PHP page?

I've noticed that my question has been asked a few times already, but I'm still struggling to get my code working. It seems like I'm using the same code as those solutions, so I can't figure out what's going wrong. Currently, I am ...

Omit child DIV element in JavaScript and the Document Object Model

I have a situation with two div elements. One is <div class="card" id="openWebsite"> and the other is a sub-division <div class="card__btn"> Here's the issue: When someone clicks on the main div, they get red ...

Sort array of objects alphabetically and move objects with value to the beginning

I have a dataset that consists of different arrays of objects. When I log myData, the output looks something like this: [ { name: 'Cdb', image: 'xxx', coll: 'xxx' }, { name: 'Bcd', image: &a ...

Manipulate a 3D shape by transforming both the x and y axes using jQuery's mousemove

I am trying to create a 3D element that rotates on both the x and y axes based on the position of the mouse on the screen. While I have successfully achieved this effect using either the X or Y position, I am struggling to make it work simultaneously for b ...

Eliminate the need for background video buffering

I have a piece of code that I'm using to remove all the created players for my video elements. The code works fine, but I'm facing an issue where the video keeps buffering in the background after it's changed via an ajax call success. Can yo ...

Sharing data between app.js and client-side files in Node.js: How to do it effectively?

I have a question about passing a value from my Node.js app.js file to my client-side JavaScript file. Here is my app.js file: var express = require('express'); var app = express(); var port = process.en ...

Design and execution of webpage structure

My website features a single-page layout with fixed navigation that allows users to easily navigate up and down the page using #. However, when the page loads I want it to display the second section of content instead of the top section. Is there a way to ...

How can I stop popup labels from appearing in MapBox GL JS when I don't want them to be visible?

Having created an application using MapBox GL JS, I have placed numerous markers all around the globe. As the mouse hovers over these markers, a description box pops up, which is what I intended. However, I am encountering an issue where these labels flick ...

Positioning icon/image beside the input box

Currently, I have a form with two buttons in a row and an icon (paper clip) that I am attempting to align next to the buttons using UIKit. However, I am facing challenges in getting the alignment right without affecting the size of the elements. Below is a ...

The Bootstrap 4 alignment class for centering rows is not functioning as expected

<div class="row align-items-center remember"> <input type="checkbox" class="form-control" checked>Remember Me </div> <div class="row align-items-center"> <input type=& ...

Tips for safeguarding registration forms against spamming

The ASP.NET/Mono MVC2 E-shop includes a registration form that requests mandatory customer name, address, phone password (entered twice) and some optional fields. Should we add spam protection to the form? The current setup verifies that the password and ...