What is the best method to override the CSS transition effect with JavaScript?

I am trying to implement a CSS transition where I need to reset the width of my box in advance every time my function is called. Simply setting the width of the box to zero makes the element shrink with animation, but I want to reset it without any animation. To achieve this, I created a class that disables and enables the effect before and after resetting the width. However, this approach is not working as expected. It seems like JavaScript is asynchronous and skips over the width=0 command quickly. I discovered that inserting an alert before removing the "notransition" class fixes the issue, but this is not a proper solution.

I have been looking for a resolution to this async problem. Any explanation and solution regarding my attempt would be greatly appreciated, along with possibly a better method for resetting the width. Thank you!

function test() {

            var duration = 5;

            document.getElementById("box").classList.add('notransition');
            document.getElementById("box").style.width = 0 + "%"
            document.getElementById("box").classList.remove('notransition');

            //Fill progress bar
            document.getElementById("box").style.setProperty('transition-duration', duration + 's');
            document.getElementById("box").style.width = 100 + "%"

            setTimeout(function () {
                console.log("Progress finished")
            }, duration * 1000);

        }
    * {
        box-sizing: border-box;
    }

    html {
        padding: 0;
        margin: 0;
        width: 100%;
    }

    body {
        margin: 0;
        width: 100%;
        padding: 20px;
    }

    #box {
        border: 1px solid red;
        height: 20px;
        width: 10%;
        background-color: rgba(219, 72, 72, 0.3);
        transition-property: width;
        transition-duration: 0s;
        transition-timing-function: linear;
    }

    .notransition {
        -webkit-transition: none !important;
        -moz-transition: none !important;
        -o-transition: none !important;
        transition: none !important;
    }
<div id="box" onclick="test()"></div>

Answer №1

Utilizing two distinct classes for toggling, specifically designed for managing the transition-delay property, has proven to work effectively. It is essential to incorporate a brief delay to ensure the width is reset to 10% before the animation commences.

function test() {

  // Setting the initial transition delay to zero seconds
  let box = document.getElementById("box");
  box.style.width = "10%";

  // Introducing a small pause (10ms) for the width update on screen
  setTimeout(function() {

    // Modifying the transition delay and adjusting the width
    box.classList.remove('normal');
    box.classList.add('transitioning');
    box.style.width = "100%";

    // Upon completion, restoring the original transition delay
    setTimeout(function() {
      console.log("Transition completed")
      box.classList.remove('transitioning');
      box.classList.add('normal');
    }, 5000);
  }, 10)
}
* {
  box-sizing: border-box;
}

html {
  padding: 0;
  margin: 0;
  width: 100%;
}

body {
  margin: 0;
  width: 100%;
  padding: 20px;
}

#box {
  border: 1px solid red;
  height: 20px;
  width: 10%;
  background-color: rgba(219, 72, 72, 0.3);
  transition-property: width;
  transition-timing-function: linear;
}

.normal {
  transition-duration: 0s;
}

.transitioning {
  transition-duration: 5s;
}
<div id="box" class="normal" onclick="test()"></div>

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 steps can I take to stop Highcharts from showing decimal intervals between x-axis ticks?

When the chart is displayed, I want to have tick marks only at integer points on the x-axis and not in between. However, no matter what settings I try, I can't seem to get rid of the in-between tick marks. Chart: new Highcharts.chart('<some i ...

How can we transfer animation duration and `@keyframe` values through a function in CSS?

In my angular project, I am currently adding animations to text. However, I want to make these animations dynamic. For instance, I have a CSS class called .slide-in-top with an animation time set to 1.3s. Instead of this static value, I want to be able to ...

I recently incorporated Puppeteer along with its necessary dependencies onto Heroku, and as a result, pushing my small app to Heroku now takes approximately 5 to 6 minutes

I am currently using Puppeteer to create a PDF from an HTML page. I installed the npm package by running the following command: npm i puppeteer However, when I deployed to Heroku, I encountered an error: Error while loading shared libraries: libnss3.s ...

What is the best way to ensure that my cards maintain consistent proportions?

My cards are not maintaining their proportions, causing buttons to pop out of the card and the card dimensions changing. I realize this issue is due to using fixed width and height in combination with flex. I'm struggling to find the best solution to ...

Having trouble loading Three.js in JavaScript file using npm install?

I am encountering a problem when trying to include Three.js in my JavaScript file without using the HTML script element. The error message I receive is "Uncaught SyntaxError: Cannot use import statement outside a module". Although my Three.js code runs suc ...

Unable to retrieve iFrame window due to an error

My challenge lies in obtaining the window of an iFrame using this particular code: var frameWindow = document.getElementById("loginframe"); var iWindow = frameWindow.contentWindow; However, I am consistently encountering this error message: Property ...

Retrieving a numerical value from a string using Javascript or JQuery

Here is an example string: "example example-5 amount-10 example direction-left" Is there a way to extract the number following "amount-", and the text immediately after "direction-" in this string? ...

To successfully process this file type in JavaScript, you might require a suitable loader

Currently, I am facing an issue with my MVC application while trying to integrate Bootstrap 5 using Webpack. Despite attempting various workarounds with stage-0, stage-2, and stage-3, none have proven successful for me. I suspect that the problem lies wit ...

Obtaining various values for checkboxes using dynamic data in a React application

Retrieve all checkbox values dynamically import * as React from "react"; import Checkbox from "@mui/material/Checkbox"; import FormControlLabel from "@mui/material/FormControlLabel"; import axios from "axios"; expor ...

Can the behavior of "flex-end" be emulated in :before and :after pseudo-elements?

I have come across a piece of code that creates a checkbox using the pseudo-elements :before and :after, along with a hidden input to handle the selection logic. The current setup works fine and behaves as expected. However, I am curious if it is possible ...

Unable to utilize the rupee font within a select element on Chrome and IE8 browsers

Issues with displaying rupee font in select element on Chrome and IE8 I have implemented WebRupee for showing the Indian currency symbol. The font appears correctly when used within a <p> tag, but when placed inside a select option element, it only ...

Using Typescript to add an element to a specific index in an array

Currently, I am engaged in a project using Angular2 and Firebase. My goal is to consolidate all query results under a single key called this.guestPush. Within my project, there is a multiple select element with different user levels - specifically 4, 6, ...

Troubleshooting: Issue with running npm start | React app not loading

npm start command seems to be stuck at this particular point - The application is failing to load because of this issue. Here is the content of package.json file - { "name": "reacttest", "version": "0.1.0", & ...

The external IP address cannot be accessed beyond the function scope in Node.js

Recently joining this community, I am in the process of retrieving my external IP through a package called "external-ip." The example code provided by them looks like this: const getIP = require('external-ip')(); getIP((err, ip) => { ...

Rendering v-html in VueJS requires a delayed binding value that can only be triggered by clicking inside and outside of a textarea control

I'm currently experiencing an issue with a textarea that is bound to a v-model with a specific value. The problem arises when the content of the textarea is changed via JavaScript - the displayed value, represented by {{{value}}}, doesn't update ...

My AngularJS module seems to be malfunctioning

After spending a significant amount of time on this, I am really hoping for some assistance. I am currently working on creating a module that will generate a directive and controller for the header section of my AngularJS site. Despite not encountering any ...

Elevate the Appearance of Material UI Elements with custom CSS Sty

I am currently facing an issue while trying to customize the styling of a Material UI component using CSS. Here is the code snippet: <IconButton className="my-class"> <Close /> </IconButton> CSS: .my-class { float: right ...

Locating the CSS pixel value without being affected by the browser's zoom settings

Check out this JS fiddle I created to illustrate my issue. As you zoom in and out of the browser page, the value of max-width that appears in the console keeps changing. However, in the CSS code it is always set to 500px. How can I retrieve the original CS ...

Generating unique ObjectIDs for each object is crucial before saving documents in Mongoose

I need to generate a unique ObjectID for every object within my array. The challenge is that I am fetching products from another server using a .forEach statement and adding them to my array without a Schema that automatically creates an ObjectID.... Prod ...

Creating HTML code using Django and JavaScript

Greetings world! I am relatively new to Python and JavaScript, so my coding techniques might seem unconventional to seasoned developers. However, I am eager to learn and improve. I have an HTML page where Django generates some code for a calendar: Here&a ...