Time for transitions to be ready for execution

0

The problem is that when I assign a transition to an element already "painted" in the DOM, it is not yet ready to execute in the next statement.

I'll illustrate:

Suppose I have the class "animate" and in that class has a transition.

.animar {
    transition: all 1s;
}

If I assign this class dynamically to a DOM element, using Javascript, and want to use the transition in the next statement, I can not do it. It would look like this:

var elemento = document.querySelector('#qualquercoisa');

// Atribuo a classe que contem a transição
elemento.classList.add('animar');

// Modifico o CSS do elemento, mas ele não é animado. O elemento é movido direto, sem nenhuma transição. 
elemento.style.marginLeft = '300px';

The way it works:

For the transition to execute, as expected, I have to do this:

 // Continuação do código acima
 setTimeout(function() {
   elemento.style.marginLeft = '600px';
 }, 10);

That is: The transition is only executed if I give it time after assigning the class, and then set the style modifications I want. It would be a kind of "time for the browser to process".

I was stuck with this because, how will I know the time it takes for the browser to be ready to run an animation on that element? This is not the most appropriate way to do this. Could someone point to some solution? Or rather, the right way, because I got it alone and I'm pretty sure it's wrong ... = P

Thank you.

    
asked by anonymous 10.10.2017 / 21:49

1 answer

0

To check when the animation finishes, add addEventListener to the element that will call a callback :

var div = document.querySelector('#div')
div.classList.add('animar');
div.style.marginLeft = '300px';
div.addEventListener("webkitTransitionEnd", callBack,false);
div.addEventListener("transitionend", callBack,false);
div.addEventListener("otransitionend", callBack,false);

window.onload = function(){
	var div = document.querySelector('#div')
	div.classList.add('animar');
	div.style.marginLeft = '300px';
	div.addEventListener("webkitTransitionEnd", callBack,false);
	div.addEventListener("transitionend", callBack,false);
	div.addEventListener("otransitionend", callBack,false);
}

function callBack(){
	alert("Fim");
}
.animar {
    transition: all 1s;
}

#div {
	width: 30px;
	height: 30px;
	background: red;
  }
<div id="div"></div>
    
10.10.2017 / 22:33