0

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.

1
  • I tried it but could not make it work. This is my very first attempt in trying something in Javascript so it could be from my end as well. Commented May 28, 2021 at 18:46

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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'.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.