Dammy Chee
Dammy Chee

Reputation: 85

Javascript onclick only works once

So I made this,

var Coin = document.getElementById("coin");

Coin.onclick = function() {
    Coin.style.webkitTransform = "rotateY(1800deg)";
    Coin.style.MozTransform = "rotateY(1800deg)";
    Coin.style.msTransform = "rotateY(1800deg)";
    Coin.style.OTransform = "rotateY(1800deg)";
    Coin.style.transform = "rotateY(1800deg)";
}

Found at: https://jsfiddle.net/dkjufqn0/

And in it, a coin spins. However, it only fires once. The first time I click it. It doesn't fire again after. Help!

Upvotes: 2

Views: 1503

Answers (2)

Nikki Koole
Nikki Koole

Reputation: 136

Are you sure about that? place a console.log(in that handler to check it)

I think your code is fine, except the rotateY calls seem to do nothing after the first click because you always set it to the same value.

Upvotes: 2

Vicky Gonsalves
Vicky Gonsalves

Reputation: 11717

Every time you click the coin it remains at the 1800 degrees, to rotate it on each click you need to increment its degrees as in below example:

https://jsfiddle.net/dkjufqn0/1/

var Coin = document.getElementById("coin");
var degrees = 0;
Coin.onclick = function() {
  degrees += 1800;
  console.log(degrees)
  Coin.style.webkitTransform = "rotateY(" + degrees + "deg)";
  Coin.style.MozTransform = "rotateY(" + degrees + "deg)";
  Coin.style.msTransform = "rotateY(" + degrees + "deg)";
  Coin.style.OTransform = "rotateY(" + degrees + "deg)";
  Coin.style.transform = "rotateY(" + degrees + "deg)";
}
body {
  -webkit-transform: perspective(500px);
  -webkit-transform-style: preserve-3d;
}

.coin {
  background-image: url("http://coins.thefuntimesguide.com/images/blogs/presidential-dollar-coin-reverse-statue-of-liberty-public-domain.png");
  background-size: 100% 100%;
  border-radius: 100%;
  height: 100px;
  margin: 50px auto;
  position: relative;
  width: 100px;
  -webkit-transition: 2s linear;
  -webkit-transform-style: preserve-3d;
}
<div class="coin" id="coin"></div>

Upvotes: 8

Related Questions