1

I want to change the the styling of an element with a function like this one

function changeStyle(element)
{
   element.style.color = 'red';
   element.style.marginLeft = '50px';
   element.style.opacity = 0.5

}

Without using setTimeOut, is there a way i can make the next change only after the previous change has taken effect? I tried using promises but all the changes still happen at the same time.

Uwem
  • 25
  • 3
  • 3
    They are not happening at the same time. All three style changes are happening one after another. It's just happening so fast that it looks like they are applied at the same time. – Hoargarth Feb 11 '21 at 11:16
  • 1
    [JavaScript Version Of Sleep](https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep) Read This – Not A Bot Feb 11 '21 at 11:16

1 Answers1

1

If you're looking for an animation effect, do you have the option of using CSS instead? Your JS code could toggle a class for example, and the CSS could handle the animation (note: I'm definitely not a CSS animation expert but just want to show how you might accomplish this):

// JS
function changeStyle(element) {
   element.className = 'animated';
}
// CSS
@keyframes changeStyle {
  0% {
    color: red;
  }

  49% {
    margin-left: 0;
  }
 
  50% {
    margin-left: 50px;
  }
  
  99% {
    opacity: 1;
  }

  100% {
    color: red;
    margin-left: 50px;
    opacity: .5;
  }
}

.animated {
  animation-name: changeStyle;
  animation-duration: 3s;
  animation-fill-mode: forwards;
}

Here's a JSFiddle to show this in action: https://jsfiddle.net/hannahska/08v93xzy/2/

Hannah
  • 933
  • 5
  • 5