Home > Software engineering >  CSS Transition ignored via JavaScript element.style.width
CSS Transition ignored via JavaScript element.style.width

Time:03-23

I'm trying to smooth out a progress bar animation when I set the new width using, as an example, document.querySelector('#mydiv').style.width = '20%' but it just updates to the new width instantly instead of following the transition. I was expecting the width to animate to the new value, perhaps I'm missing something obvious or have a basic misunderstanding of the transition property. Here's the element, advice appreciated:

setTimeout(function() {
  document.querySelector('#mydiv').style.width = '20%';
}, 500);
#mydiv {
  position: absolute;
  top: 0;
  left: 0;
  width: 0;
  height: 0.4rem;
  background: orange;
  transition: width 1s ease-out;
}
<div id="mydiv"></div>

CodePudding user response:

You have 2 timing functions in the transition property: linear and ease-out. See here for the shorthand https://developer.mozilla.org/en-US/docs/Web/CSS/transition

CodePudding user response:

It's working, I was repainting the div so the transition had no basis.

Refactored accordingly and it works fine.

Thanks everybody for chiming in and getting me to the issue.

  • Related