What is the best way to set the keyframes CSS value for an element to 0%?

Would like to create a progress indicator div using CSS animations? Check out the JSBin link provided. The desired behavior is to have the div width increase from 30% to 100% when the user clicks on stage3 after stage1, rather than starting from 0%. Although setting the initial width as 30% would achieve this, it may not be practical for multiple stages. The goal is for the animation to start from the final width of the last stage and then transition to the new stage's specified width.

Progress indicator snippet

document.getElementById('stage1').addEventListener('click', function() {
  document.getElementById('progress').classList.add('stage1');
}, false);

document.getElementById('stage2').addEventListener('click', function() {
  document.getElementById('progress').classList.add('stage2');
}, false);

document.getElementById('stage3').addEventListener('click', function() {
  document.getElementById('progress').classList.add('stage3');
}, false);
.progress-wrapper {
  height: 10px;
  width: 400px;
  background-color: #BBDEFB;
}
#progress {
  background-color: #AADE00;
  height: 10px;
  width: 0;
}
.stage1 {
  animation-name: stage1;
  animation-duration: 1s;
  animation-fill-mode: forwards;
}
@keyframes stage1 {
  to {
    width: 30%;
  }
}
.stage2 {
  animation-name: stage2;
  animation-duration: 1s;
  animation-fill-mode: forwards;
}
@keyframes stage2 {
  to {
    width: 70%;
  }
}
.stage3 {
  animation-name: stage3;
  animation-duration: 1s;
  animation-fill-mode: forwards;
}
@keyframes stage3 {
  to {
    width: 100%;
  }
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>

<body>
  <div class="progress-wrapper">
    <div id="progress"></div>
  </div>
  <pre>
    
  </pre>
  <button id="stage1">stage1</button>
  <button id="stage2">stage2</button>
  <button id="stage3">stage3</button>
</body>

</html>

Answer №1

As far as I know, there isn't a pure CSS solution for this issue. However, one workaround is to set the width of the progress element before adding the designated class.

By doing this, the transition will happen from the previous width rather than starting at 0.

var progressBar = document.getElementById('progress');
  
document.getElementById('stage1').addEventListener('click', function() {
  savePreviousWidth();
  progressBar.classList.add('stage1');
}, false);

// Repeat above pattern for stage2 and stage3

function savePreviousWidth() {
  progressBar.style.width = progressBar.offsetWidth + 'px';
}
.progress-bar-wrapper {
  height: 10px;
  width: 400px;
  background-color: #BBDEFB;
}
#progress {
  background-color: #AADE00;
  height: 10px;
  width: 0;
}

/* Animation stages */

.stage1 {
  animation-name: stage1;
  animation-duration: 1s;
  animation-fill-mode: forwards;
}
@keyframes stage1 {
  to {
    width: 30%;
  }
}

/* Include similar styles for stage2 and stage3 */

}
<div class="progress-bar-wrapper">
  <div id="progress"></div>
</div>
<button id="stage1">Stage 1</button>
<button id="stage2">Stage 2</button>
<button id="stage3">Stage 3</button>

Answer №2

utilize a custom CSS variable:

  1. establish a custom variable in your CSS, for example

element{ --custom_variable: 0; }

  1. retrieve the current property value using JavaScript and assign it to the custom variable, for instance, if you require the color value of an element <p> :

element = querySelector("p");  //or any other selector
computed_element = getComputedStyle(element);
current_color = computed_element.getPropertyValue("color")
computed_element.setProperty("--custom_variable",current_color);

  1. apply that variable in a CSS keyframe, such as

@keyframes{
0%{ color: var(--custom_variable) }
100% { ..... }
}

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

Nested Property Binding in CallByName

I am looking to utilize CallByName in VBA to extract specific data from various webpages with differing html structures. In my scenario, I need to reference multiple parent nodes to access an element with or tags. Here is an example of the code: The eleme ...

Getting text between Span tags using Selenium in Python

Struggling to extract the name "Margaret Osbon" from the following HTML using Python and Selenium. Despite trying different techniques, the printed output always comes out blank. <div class="author-info hidden-md"> By (autho ...

Position an element in CSS relative to two other elements

Can an element be positioned horizontally in relation to one element and vertically to another using only CSS? I am attempting to include a dropdown menu in my navbar. However, the submenu is not aligning correctly. I want to position element A so that its ...

The dispatch function in redux-thunk is not functioning as expected

Having trouble with thunk and async dispatching? Check out this code snippet: function fetchProvider() { return (dispatch) => { graphqlService(fetchProviderQuery) .then((result) => { dispatch({ type: FETCH_PROVIDER, ...

Using AJAX to update the value of a div by clicking within a PHP loop

I'm currently working on a php page where I want to dynamically change the content of a div when a specific link is clicked. The links are generated through a loop, and I need to pass multiple parameters via the URL. Since the divs are also created wi ...

Interactive KML layer in ArcGIS mapping tool

Currently, I am working on enhancing an ArcGIS map by incorporating KML layers for interactivity. This is a simplified version of the code I am currently using: map = new Map("map", { basemap: "topo", center: [-108.663, 42.68], zoom: 6 }); parser.p ...

Using a loop in a Vue.js slick slider: easy step-by-step guide

While utilizing vue-slick link https://www.npmjs.com/package/vue-slick within a bootstrap modal, I encountered an issue when using a v-for loop to iterate through the items. The problem can be seen in this example: . Below is an excerpt of my code: imp ...

Tips for passing a URL variable into an Ajax script to prefill a form input in a search field

I have a website with a search feature that dynamically queries a database as you type in the search field, similar to Google's search suggestions. This functionality is achieved through AJAX. As the results appear on the page while you enter your se ...

Substitute link with asynchronous JavaScript and XML

I need to enable/disable user accounts by clicking on an anchor. The list of users is created dynamically using a loop. Here's an example of an anchor tag: <a href="http://www.example.com/users/deactivate/44" class="btn btn-success" title="Deactiv ...

Switch the placement of two DIV elements by their corresponding IDs

I am attempting to adjust the position of two divs using jQuery, but I seem to be a bit confused as they are already swapping positions. However, when they do swap, it results in a duplication of the field. I have tried using both insertBefore and insertA ...

"Troubleshooting: Ajax error 'Uncaught ReferenceError: data is not defined' on the

Upon checking the Chrome console, the error message displayed is : Uncaught ReferenceError: data is not defined function list(){ $.ajax({ type:'POST', url:'adeneme.php', data:$('#form1').seri ...

Express.js and gridfs-stream are unable to retrieve the error

Imagine an effortless image download server where Express.js takes the request, fetches an image from MongoDB GridFS, and serves it as a response. Everything works fine when the request is valid and the file exists. The issue arises when it fails to catc ...

Utilize CSS to selectively apply the mix-blend-mode property to targeted elements

In my project, I am aiming to utilize the mix-blend-mode property to give certain SVG paths the appearance of an erasing path by blending them with a background image on the stroke. However, I have encountered a challenge where the mix-blend property affec ...

Issue with dropdown menu appearing beneath specific elements in Internet Explorer versions 7 and 8

I've been encountering some troublesome issues with a website I'm working on, specifically in Internet Explorer 7/8. On certain pages, the navigation elements are getting hidden below text and images, causing confusion for me. I've attempted ...

`Implementing a dynamic list with image and button using Bootstrap 5`

I've been exploring ways to create a container with 4 images aligned next to each other, accompanied by a button beneath each image. My goal is for the layout to be responsive, meaning that as the screen size adjusts, the elements inside should also a ...

Do I have to include 'document.ready()' for this JavaScript code snippet?

I am currently utilizing freemarker to dynamically generate HTML pages based on user requests. These pages contain a reference to a javascript file in the header section. Within this javascript file, there is an array that is defined. It is necessary for m ...

The backbone view is having trouble processing the data from this.model.toJSON()

I've been working on a Backbone code implementation to display all modifications before adding data to my model. However, every time I try to add something from my form, my view returns "this.model.toJSON() is not a function" and I can't figure o ...

Looking for a PHP add-on for fpdf converter that can handle ul li tags

I need assistance with using fpdf to convert dynamic site content to pdf. The issue is that fpdf does not support ul li tags. Is there an add-on available for fpdf that supports ul li and ol li tags in html? To provide more context: The content being con ...

Empty text box

I've been attempting to clear ng-model inputs, but haven't had any success and I can't seem to figure out why. Here is what I have: <button ng-click="$ctrl.clear()"></button> And in the clear action, I have: $scope.$event = n ...

Check the validity of your JavaScript files with our convenient online tool!

Is there a website or online tool available to validate the syntax of JavaScript code in a file? I am experiencing problems with Internet Explorer 7 while running JavaScript, so I want to make sure my JavaScript file is valid. ...