2

I wanted to calculate the computed height of a list. On IE, these two give different results. On Chrome, the value seems to be always on integer, so I do not get this problem.

// gives a string of "353.7px"
window.getComputedStyle(mylist, null).getPropertyValue("height") 

// gives an int of 354
$(mylist).height(); 

How come jQuery drops decimals, or is this a problem with IE?

EDIT I was actually lying. This happens with Chrome. See http://jsfiddle.net/jTPk9/

CookieEater
  • 2,237
  • 3
  • 29
  • 54
  • If anyone is to be blamed, blame IE. jQuery will internally use one of the browser provided methods to get this value, which IE (as always) has got wrong. – techfoobar Feb 14 '14 at 11:11
  • Seems like this happens on Chrome, too. Please see the jsFiddle I added. – CookieEater Feb 14 '14 at 11:17

2 Answers2

3

This is a known bug in jQuery, which shouldn't round height and width values.

http://bugs.jquery.com/ticket/9628

Updated with @CookieMonster's comment

The current workaround is to use .getBoundingClientRect().height, which is cross browser and doesn't round values.

document.getElementById("fruits").getBoundingClientRect().height
Adam Hopkinson
  • 28,281
  • 7
  • 65
  • 99
  • 1
    Just a note for future visitors. Current workaround is to use `.getBoundingClientRect().height`. This works across browsers and does not round up the value. – CookieEater Feb 19 '14 at 09:27
1

For those coming here later, this was fixed in jQuery 3.0 to use the getBoundingClientRect API mentioned in the accepted answer. If you're using an older version of jQuery (for example, I was dealing with jQuery 1.12.4), $(element).width() and $(element).height() will always round to the nearest integer.

Tommy
  • 95
  • 1
  • 9