Dwight Schrute
Dwight Schrute

Reputation: 57

Rotate element on each click

I am trying to rotate an element on each click like this: https://uimovement.com/design/addition-subtraction/

I tried this:

element.style = 'tranform: rotate(90deg)'

But this adds style only once. I want to rotate it on each click. How do I do that?

I tried adding a class. But when I click once, the class gets added, so I cannot add again. If I remove the class to enable rotate on next click, the rotate happens in the reverse direction.

Edit : https://jsfiddle.net/8pue5nra/

Upvotes: 2

Views: 1776

Answers (2)

ellipsis
ellipsis

Reputation: 12152

You can make a function and you have to change the angle on every click. Add a counter and multiply it with 90 for every click to rotate it every time on click.

var count=0;
function rot(e){
count++;
var deg=count*90;
 e.style.transform = "rotate("+deg+"deg)";
}
#box
{
height:20px;
width:70px;
background-color:yellow
}
<div id="box" onclick="rot(this)"></div>

Upvotes: 3

Gabriel Vasile
Gabriel Vasile

Reputation: 2348

Use this

const el = document.querySelector('#btn');
let degrees = 0;

el.addEventListener('click', function(){
  degrees += 90;
  this.style = `transform: rotate(${degrees}deg)`;
})

Upvotes: 2

Related Questions