How to avoid css conversion (rotate) when deleting a class?

I want to rotate the onclick element by adding a CSS class to it. The problem is that when the same CSS class is removed, the element rotates a second time.

script: https://jsfiddle.net/L3x2zhd1/1/

JS:

var el = document.getElementById('el'); el.onclick = function() { el.className = 'rotate' setTimeout(function(){ el.className = '' },1000) }; 

CSS

 #el { width: 50px; height: 50px; background-color: red; -webkit-transition: -webkit-transform 1s; transition: transform 1s; } .rotate { -webkit-transform: rotate(180deg); transform: rotateX(180deg); } 

How can i avoid this?

+5
source share
2 answers

You want to put transition: transform 1s (and its provider prefixes) in the .rotate css rule:

Reason for double animation: You have defined a transition property on the root element. As a result, when he tried to reach his normal position, he again rotated due to transition .

 var el = document.getElementById("el"); el.addEventListener("click", function() { el.classList.add("rotate"); setTimeout(function() { el.classList.remove("rotate"); }, 1000); }); 
 #el { width: 50px; height: 50px; background-color: red; } .rotate { -webkit-transition: -webkit-transform 1s; transition: transform 1s; -webkit-transform: rotateX(180deg); transform: rotateX(180deg); } 
 <div id="el"></div> 
+6
source

You can simply switch the class, and not add or remove it.

 $('#el').click(function(){ $(this).toggleClass('rotate'); }); 
 #el { width: 50px; height: 50px; background-color: red; -webkit-transition: -webkit-transform 1s; transition: transform 1s; } .rotate { -webkit-transform: rotate(180deg); transform: rotateX(180deg); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="el"></div> 
0
source

Source: https://habr.com/ru/post/1258487/


All Articles