Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid css transformation(rotate) when removing class?

Tags:

javascript

css

I want to rotate element onclick by adding CSS class to it. Problem is, when that same CSS class is removed, element is rotated for the second time.

fiddle: 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?

like image 506
11223342124 Avatar asked Oct 19 '16 15:10

11223342124


1 Answers

You'll want to place the transition: transform 1s (and related vendor prefixes) on the .rotate css rule:

Reason for double animation: You had defined the transition property on the root element. As a result when it was trying to come to its normal position, it was again rotating 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;
  color: white;
  font-weight: bold;
  text-align: center;
}

.rotate {
  -webkit-transition: -webkit-transform 1s;
  transition: transform 1s;
  -webkit-transform: rotateX(180deg);
  transform: rotateX(180deg);
}
<div id="el">test</div>
like image 164
mhodges Avatar answered Nov 05 '22 22:11

mhodges