11

I need to obtain actual height of several different elements (for the sake of precise custom tooltip positioning), and some of these elements (not all) are rotated. $(elem).outerHeight() returns the original height, instead of the actual displayed height.

Here's the fiddle with a very simple example: http://jsfiddle.net/NPC42/nhJHE/

I see a possible solution in this answer: https://stackoverflow.com/a/8446228/253974, but am still hoping there is a simpler way.

Community
  • 1
  • 1
NPC
  • 1,009
  • 3
  • 10
  • 27

2 Answers2

10

Dusting off my high school geometry and my formidable graphics skills, I put this diagram together. If you have variables width, height, and rotation in javascript, you could express the height this way:

var rotated_height = width * Math.sin(rotation) + height * Math.cos(rotation);

enter image description here

Starx
  • 77,474
  • 47
  • 185
  • 261
recursive
  • 83,943
  • 34
  • 151
  • 241
  • 1
    Thanks for the edit Starx. That was a pretty crucial error in the most important part of the post! – recursive Mar 20 '12 at 19:04
  • Thanks, I understand that, but you missed that I am processing several elements, only some of which are rotated. I am looking for a universal method "get the height of an element", without pre-knowing that it has been rotated. But if I can't find it - I'll have to use this method, yes :) Thanks again! – NPC Mar 20 '12 at 19:32
  • @NPC: If the rotation is 0, this method still works with no special cases, since `sin(0) == 0` and `cos(0) == 1`. – recursive Mar 20 '12 at 19:36
  • 1
    Yes, but this requires knowing of rotation. As there are no better solutions, I accept yours, but in reality it requires dealing with a transform matrix. I created a fiddle that demonstrates this, if anyone (me included :)) will ever need it in the future: http://jsfiddle.net/NPC42/nhJHE/ (but seeing this monster I think it is better to change the algorithm to put some class on rotated items, to avoid the nightmare). – NPC Mar 21 '12 at 13:24
1

If you're only going to be using rotations of 45 degrees and the width and height are always equal, you can calculate the actual rotated height by using the relatively simple mathematical Hypotenuse formula:

which states that the square of the length of the hypotenuse equals the sum of the squares of the lengths of the other two sides.

In this case, the longest side would be the diagonal from corner to opposing corner. This will roughly translate into jQuery like so:

Math.sqrt(Math.pow($('#diamond').height(), 2) + Math.pow($('#diamond').width(), 2))

See the updated jsFiddle.

Goran Mottram
  • 6,244
  • 26
  • 41
  • Same as above - Thanks, but you missed that I am processing several elements, only some of which are rotated. But - thanks for answering. – NPC Mar 20 '12 at 19:33