Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change @keyframes using JS? [duplicate]

I'm using

#progressBar{
   background-color: #247BA0;
   width: 150px;
   padding: 10px;
   border-radius: 5px;
   animation: progressBar 3s ease;
   animation-fill-mode:both; 
   text-align: center;
   box-sizing: content-box;
} 

and

@keyframes progressBar {
 0% { width: 0; }
100% { width: 280px; }
}

I want to change the width number of @keyframeusing a JS variable. How could I do this (whithout jQuery) ?

like image 694
Felipe Donizete Avatar asked Jul 12 '26 14:07

Felipe Donizete


1 Answers

you can use css variables for this case.

define two variable in root of page and use these in keyframe :

:root {
    --my-start-width: 0;
    --my-end-width: 280px;
}

...

@keyframes progressBar {
    0% { width: var(--my-start-width); }
    100% { width: var(--my-end-width); }
}

now you can get and set this property in js with these functions :

//set property: 

document.documentElement.style
    .setProperty('--my-variable-name', '100px');

//get property

getComputedStyle(document.documentElement)
    .getPropertyValue('--my-variable-name'); // returns value

like image 172
alefseen Avatar answered Jul 15 '26 02:07

alefseen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!