jolt jolt - 4 months ago 29
jQuery Question

width/height after transform

How do I retrieve the width and height properties after I've applied

transform: rotate(45deg);
?

Like, 11x11 square after rotation becomes 17x17 (Chrome result), but javascript still returns original width/height - 10x10.

How do I get this 17x17?

Answer

Even if you rotate something the dimensions of it do not change, so you need a wrapper. Try wrapping your div with another div element and count the wrappers dimensions:

  <style type="text/css">
  #wrap {
    border:1px solid green;
    float:left;
    }

  #box {
    -moz-transform:rotate(120deg);
    border:1px solid red;
    width:11px;
    height:11px;
  }
  </style>

  <script type="text/javascript">
  $(document).ready(function() {
    alert($('#box').width());
    alert($('#wrap').width());
  });
  </script>
</head>

<body>
 <div id="wrap">
  <div id="box"></div>
  </div>
</body>

Redited: the wrapper solution is not working properly, as the wrapper is not automatically adjusted to the contents of the inner div. Follow the mathematical solution:

var rotationAngle;

var x = $('#box').width()*Math.cos(rotationAngle) + $('#box').height()*Math.sin(rotationAngle);