Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotate div-element with every click on a button [duplicate]

Tags:

javascript

css

To the point: The content-div rotates 360 degrees when the button is clicked. But, on the 2nd click, nothing happens.

What I want, is that on every click on the button the div-element rotates 360 degrees, just like it does on the first click.

I have found some jQuery suggestions, but I wish to accomplish this by using JavaScript.

var content = document.getElementById("content");
var btn = document.getElementById("btn");
btn.addEventListener("click", function() {
  content.style = 'transform: rotate(' + 0 + '360deg)';
});
#content {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background: lightblue;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 1s ease-in-out;
}

#btn {
  width: 100px;
  height: 50px;
  background: grey;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  text-decoration: none;
}

a {
  color: white;
  text-decoration: none;
}
<div id="content">
  <p>It's spinning</p>
</div>
<div id="btn"><a href="#">Click</a></div>
like image 576
Tane Avatar asked Sep 11 '19 12:09

Tane


1 Answers

You just need to keep adding 360!

var content = document.getElementById("content");
var btn = document.getElementById("btn");
var rot = 360;
btn.addEventListener("click", function() {
  content.style = 'transform: rotate(' + rot + 'deg)';
  rot += 360;
});
#content {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background: lightblue;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 1s ease-in-out;
}

#btn {
  width: 100px;
  height: 50px;
  background: grey;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  text-decoration: none;
}

a {
  color: white;
  text-decoration: none;
}
<div id="content">
  <p>Its spinning</p>
</div>
<div id="btn"><a href="#">Click</a></div>
like image 104
Patrick Lüthi Avatar answered Oct 17 '22 03:10

Patrick Lüthi