6

I am trying to get the height of an element in JavaScript after applying one/several CSS3 transformations on it.

#transformed{
    transform:scale(.5);
}

Unfortunately, JQuery's outerHeight doesn't seem to do this naively.

$('#after').outerHeight(); //not affected by the transformation

Example: http://jsfiddle.net/mQ2nT/

Musa
  • 96,336
  • 17
  • 118
  • 137
ipburbank
  • 151
  • 1
  • 8

1 Answers1

11

You can use getBoundingClientRect to get the dimensions and positions after the transformation.

Simply, transform your elements, and:

$('#after')[0].getBoundingClientRect();
// note the [0], the function is DOM not jQuery's.

The best thing is that this will also return proper positions, dimensions after every transformation you apply.

You are free to rotate, skew, translate and everything else what CSS provides. gBCR will handle it.

tomsseisums
  • 13,168
  • 19
  • 83
  • 145
  • Very nice! Didn't even think of it. – Benjamin Powers Dec 01 '12 at 23:56
  • @Musa: Out of curiosity, is there a way to query `getBoundingClientRect` including the margins? When running your fiddle in Chrome and applying a margin to the divs, jquery can use `outerHight(true)` to include margins but they seem to be ignored by the `getBoundingClientRect.height()` property. See here: http://jsfiddle.net/mQ2nT/4/ – Nope Dec 02 '12 at 00:14
  • @FrançoisWahl, no. Margin isn't part of bounding box. – tomsseisums Dec 02 '12 at 00:21
  • According to [this article](http://help.dottoro.com/ljvmcrrn.php), if using `getBoundingClientRect` `in IE7 or older, the returned object contains the coordinates in physical pixel size, while from version 8, it contains the coordinates in logical pixel size.` This seems to only matter though when zooming I gathered. +1 @psycketom though as I think `getBoundingClientRect` is my personal preferred option too (now that I learned about it), unless I need to include margins or for some reason have to support zooming in IE7 or older. – Nope Dec 02 '12 at 00:29
  • @FrançoisWahl, CSS3 transforms and IE<9 doesn't make sense at all. As for the margins, that's an easy addition to gBCR. – tomsseisums Dec 02 '12 at 00:39
  • @psycketom: Complete oversight on my behalf. Never dawned on me. You are correct off course. I'm going to remove my answer as it seems it is completely redundant to calculate your own size based on scale, seeing that `getBoundingClientRect` takes care of everything. As you said, if margins are to be taken into account it is easy to add. Even a simple `outerHeight(true) - outerHeight()` will do. – Nope Dec 02 '12 at 00:43