Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly wait until JavaScript applies inline Css

Tags:

javascript

css

I have this jsFiddle. When the button is clicked, I want to put the red div behind the black one immediately, then start the animation.

var red = document.getElementById("red");
var button = document.getElementById("button");

button.addEventListener("click",function () {
    red.style.zIndex = -1;
    red.classList.remove("shifted");
});

However, as you can see, they seem to be occurring as two separate actions. I know I can use setTimeout to wait until the zIndex property is applied, but I do not know how long I am supposed to wait, and the duration perhaps differs from browsers to computers.

Should I create a loop that will check if zindex was applied? But this also sounds like an unintelligent solution. What is the correct way?

EDIT: I do not want to change the zIndex on the black div.

like image 252
CookieEater Avatar asked Jan 28 '26 08:01

CookieEater


1 Answers

You can bind to the transitioned state of the element, something like this:

("#mySelector").bind("transitionend", function(){ 'yourcodehere' });

Also, here is some info on it:

  • https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_transitions
  • https://developer.mozilla.org/en-US/docs/Web/Reference/Events/transitionend

Without jQuery:

el.addEventListener("transitionend", updateTransition, true);

Edit:

There was some confusion as to the usage of:

-webkit-transition-duration: 1s;

This is applied like a styling as well. So anytime you make alterations to the element it is on, you are triggering this. You have TWO transition calls, one for setting the z-index, another for the movement.

like image 105
Organiccat Avatar answered Jan 30 '26 21:01

Organiccat