7

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>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Tane
  • 481
  • 2
  • 9
  • 20
  • The jQuery dupe is very easy to translate into something you can use: `var r = 0; $('#icon').click(function(){ $(this).css('transform','rotate(' + (r += 360) + 'deg)'); });` – mplungjan Sep 11 '19 at 13:02

1 Answers1

9

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>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Patrick Lüthi
  • 324
  • 2
  • 12