I have the following CSS Keyframe:
@keyframes progressStatus
{
to
{
stroke-dashoffset: 165;
}
}
I am trying to change the value 165 to something else with Javascript.
I have the following CSS Keyframe:
@keyframes progressStatus
{
to
{
stroke-dashoffset: 165;
}
}
I am trying to change the value 165 to something else with Javascript.
For this particular example you could use a CSS variable.
This simple snippet alters a variable called --strokeDashoffset every time the div is clicked (and toggles between having an animation and not, just for the demo).
div {
--strokeDashoffset: 165px; /* initial position */
background-color: magenta;
width: var(--strokeDashoffset);
height: 5vmin;
animation: none;
animation-fill-mode: forwards;
animation-duration: 1s;
animation-iteration-count: 1;
}
.strokeDashoffset {
animation-name: progressStatus;
}
@keyframes progressStatus
{
to
{
stroke-dashoffset: var(--strokeDashoffset);
}
}
<div onclick="this.classList.toggle('strokeDashoffset'); this.style.setProperty('--strokeDashoffset', Math.random(0,1)*100 + 'vmin');" >CLICK ME</div>
While the CSS variable approach in the other answer is nicer, here is one that modifies the relevant CSS directly since I already typed it out. This might be useful if you can't rely on CSS custom properties (variables) or a polyfill.
In the CSS Object Model, a @keyframes rule has its own array of child rules corresponding to the keyframes themselves (from, to and/or percentages). So, if your example were the first stylesheet in the document (and had no other rules):
const stylesheet = document.stylesheets[0];
const progressStatus = stylesheet.cssRules[0];
const toKeyframe = progressStatus.cssRules[0];
toKeyframe.style.strokeDashoffset = '170 80'; // or whatever desired value
Picking stylesheets and nested rules by array indexes is cumbersome, error-prone and easily breaks with changes. In production code, you'll at least want to locate the rule by iterating through all rules with various tests, like rule.type === CSSRule.KEYFRAMES_RULE && rule.name === 'progressStatus'.