0

I've got an element that I want to determine its height and width so I can fill it properly, but when I use

$('#element').height();
$('#element').width();

it returns the values in percentages. I've been looking for a solution, but all the questions that come up in my searches imply that jQuery returns the pixels by default, and so do not explain how to get it to do so.

Rorrik
  • 270
  • 1
  • 3
  • 15
  • 1
    http://api.jquery.com/height/ – ryanlutgen Feb 03 '15 at 03:31
  • 1
    This page indicated that the value may not be accurate if the parent was hidden. I never imagined "may not be accurate" would mean percentage is returned instead of pixels. – Rorrik Feb 03 '15 at 04:02

2 Answers2

2

I believe you must be mistaken. Can you provide a demonstration where jQuery is returning a percent value for .width or .height?

Jack
  • 9,448
  • 3
  • 29
  • 33
  • 1
    Thank you! In my attempt to produce an example for you I found the problem was that I was finding the height and width while its parent was hidden. Doing it when the div is shown produces the right result. – Rorrik Feb 03 '15 at 03:58
0

What exactly is being returned? You may be seeing a fractional value (.75) instead of an integer. From the .height() documentation:

The number returned by dimensions-related APIs, including .height(), may be fractional in some cases. Code should not assume it is an integer. Also, dimensions may be incorrect when the page is zoomed by the user; browsers do not expose an API to detect this condition.

  • The exact percentage set in the CSS was being returned. Is this normal when the parent is hidden? – Rorrik Feb 03 '15 at 03:59
  • How are you hiding the parent; `display: none` or `visibility: hidden`? – asalexander Feb 03 '15 at 14:39
  • Without having seen your code, I would suggest you force layout on the parent so you can get accurate height and width of the child. There are several solutions here on Stack Overflow. http://stackoverflow.com/questions/9117738/jquery-getting-a-hidden-elements-height http://stackoverflow.com/questions/9117738/jquery-getting-a-hidden-elements-height – asalexander Feb 03 '15 at 17:21
  • Thank you, I have found a solution, I simply show the parent before getting the values and then hide it again. – Rorrik Feb 03 '15 at 20:23