2

I have this div

<div style="transform: scale(2,3)"></div>

How do I get the

transform: scale(x,y) 

of an element using JS or jQuery.

$('#id').css('transform') 

gives me the matrix but i need the actual scale values from my element. Or if I cannot get the scale directly then what is the calculation to convert the matrix() to scale if I have

var mt = matrix(....); how do I then convert mt[0] and mt[3] to actual scale values.
russ
  • 103
  • 1
  • 7

4 Answers4

3

var m = $('#id').css('transform');
var mt = m.substring(m.indexOf('(') + 1, m.indexOf(')')).split(',');
// or else: var mt = m.substring(7, m.length - 1).split(',');
console.log(mt[0], mt[3]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='id' style="transform: scale(2,3)"></div>

You can put a plus sign in front of the array elements to ensure they are treated as numeric.

Kent Weigel
  • 1,168
  • 1
  • 11
  • 16
2

Possible duplicate of Get the scale value of an element?:

var matrixRegex = /matrix\((-?\d*\.?\d+),\s*0,\s*0,\s*(-?\d*\.?\d+),\s*0,\s*0\)/;
var matches = $('#id').css('transform').match(matrixRegex);
console.log(matches)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="id" style="transform: scale(2,3)"></div>

That snippet will return an array with the original matrix, and then indexes 2 and 3 contain X and Y values, respectively. Credit to Lea Verou

JonLuca
  • 850
  • 6
  • 25
0
<div id="container" style="transform: scale(2,3)"></div> 

and then

var vals = $('#container').css('transform').replace(/\(|\)|scale/g,'').split(',')

Now, you have the scale values in vals as string, just parse parseFloat(vals[0]) and parseFloat(vals[1]) to number to get the value of x and y

Koushik Chatterjee
  • 4,106
  • 3
  • 18
  • 32
-2

Try this HTML

<div id="container" style="transform: scale(2,3)"></div>    

Try this JS

console.log($('#container').attr('style'))
Sourabh Somani
  • 2,138
  • 1
  • 13
  • 27