maja
maja

Reputation: 187

How to get style transform rotate value in javascript?

I need transform rotate value...? alert("rotate(30deg)")...

<div id="demo" style="transform: rotate(30deg);width:100px;height:50px;background-color:red;">
var myElement = document.getElementById("demo");
var rotate = getElementById("demo").style.transformRotate.value;
alert(rotate);

Upvotes: 1

Views: 3185

Answers (2)

Rick Hitchcock
Rick Hitchcock

Reputation: 35670

You could parse the transform style using match to get the rotate value:

var myElement = document.getElementById("demo");
var rotate = myElement.style.transform.match(/rotate\((.+)\)/);
alert(rotate && rotate[1]);  // avoid error if match returns null
<div id="demo" style="transform: rotate(30deg);width:100px;height:50px;background-color:red;">

To separate the number (30) from the unit (deg), you could do the following:

var myElement = document.getElementById("demo");
var rotate = myElement.style.transform.match(/rotate\((\d+)(.+)\)/);
if (rotate) {
  var [num, unit] = rotate.slice(1);  // slice is needed since first element contains entire match
  console.log('num:', num, 'unit:', unit);
}
<div id="demo" style="transform: rotate(30deg);width:100px;height:50px;background-color:red;">

Upvotes: 4

0bero
0bero

Reputation: 1062

You need to store transform not transformRotate:

var myElement = document.getElementById("demo");
var transformation = myElement.style.transform;
alert(transformation);
<div id="demo" style="transform: rotate(30deg);width:100px;height:50px;background-color:red;">

Upvotes: 1

Related Questions