Skip to content
Advertisement

How do you read the rotation of a div using javascript?

I have a spinning wheel that I need to read the rotation for. It spins and stops, then I need to read the rotation to know how many points to assign to it. (the wheel with point values on it). How would I do this? I would think that it would be document.querySelector(".container").style.transform.rotate but it returns NaN.

This is the code I’m using to rotate the wheel.

var spinInterval = 0;
function timeSpin() {
  var loop = setInterval(function () {
    let spin = Math.round(Math.random() * 100);
    spinInterval += spin;
    let rotate = `rotate(${spinInterval}deg)`;
    document.querySelector(".container").style.transform = rotate;
    // console.log(rotate);
    rotation = spinInterval;
  }, 100);

  setTimeout(function () {
    clearInterval(loop);
  }, 5000);
}

Advertisement

Answer

You can simply access the final rotation in the callback of the outer setTimeout.

setTimeout(function () {
  clearInterval(loop);
  // inline style.transform
  console.log(document.querySelector(".container").style.transform);
}, 5000);

// rotate(2279deg)

Alternatively You can use window.getComputedStyle() to return the full computed transform matrix. You’ll need to parse it from there.

setTimeout(function () {
  clearInterval(loop);
  // full computed transform matrix
  const rotation = window.getComputedStyle(document.querySelector(".container")).getPropertyValue('transform');
  console.log(rotation);
}, 5000);

// matrix(-0.7880107536067242, -0.6156614753256553, 0.6156614753256553, -0.7880107536067242, 0, 0)

A rundown of the math on CSS-Tricks:Get Value of CSS Rotation through JavaScript or in this answer: How to get CSS transform rotation value in degrees with JavaScript

var spinInterval = 0;
function timeSpin() {
  var loop = setInterval(function () {
    let spin = Math.round(Math.random() * 100);
    spinInterval += spin;
    let rotate = `rotate(${spinInterval}deg)`;
    document.querySelector(".container").style.transform = rotate;
    // console.log(rotate);
    rotation = spinInterval;
  }, 100);

  setTimeout(function () {
    clearInterval(loop);
    console.clear();
    // inline style.transform
    console.log(document.querySelector(".container").style.transform);

    // full computed transform matrix
    const rotation= window.getComputedStyle(document.querySelector(".container")).getPropertyValue('transform');
    console.log(rotation);
  }, 5000);
}

document.querySelector('button').addEventListener('click', timeSpin);
.container {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  border-right: 8px solid yellow;
  border-left: 8px solid lightgray;
  border-top: 8px solid aqua;
  border-bottom: 8px solid pink;
 }
<div class='container'></div>
<button type='button' >Spin</button>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement