Do not round .width() in jQuery

I’ve searched around and couldn’t find this. I’m trying to get the width of a div, but if it has a decimal point it rounds the number. example: #containerbackground: blue;width: 543.5px;height: 20px; margin: 0;padding: 0; if I do $(‘#container’).width(); it will return 543 instead of 543.5. How do I get it to not round the …

via Css Website development » Search Results » ajax:

Do not round .width() in jQuery

I’ve searched around and couldn’t find this. I’m trying to get the width of a div, but if it has a decimal point it rounds the number.
example:
#container
background: blue;
width: 543.5px;
height: 20px;

margin: 0;
padding: 0;

if I do $(‘#container’).width(); it will return 543 instead of 543.5. How do I get it to not round the number and return the full 543.5 (or whatever number it is).
Thanks.
……………………………

I don’t think browsers will use fractional dimensions internally. The .width() returns the computed width, which the rendering engine should have already rounded to integer.
You could use .css(‘width’), which should return “543.5px” on some browsers (e.g. Firefox (Gecko)).
……………………………

Just wanted to add my experience here, though the question’s old: The consensus above seems to be that jQuery’s rounding is effectively just as good as an unrounded calculation — but that doesn’t seem to be the case in something I’ve been doing.
My element has a fluid width, generally, but content that changes dynamically via AJAX. Before switching the content, I temporarily lock the dimensions of the element so my layout doesn’t bounce around during the transition. I’ve found that using jQuery like this:
$element.width($element.width());is causing some funniness, like there are sub-pixel differences between the actual width and the calculated width. (Specifically, I will see a word jump from one line of text to another, indicating the the width has been changed, not just locked.) From another question — Getting the actual, floating-point width of an element — I found out that window.getComputedStyle(element).width will return an unrounded calculation. So I changed the above code to something like
var e = document.getElementById(‘element’);
$(‘#element’).width(window.getComputedStyle(e).width);And with THAT code — no funny bouncing! That experience seems to suggest that the unrounded value actually does matter to the browser, right? (In my case, Chrome Version 26.0.1410.65.)
……………………………

Use the native getBoundingClientRect rather than the style of the element. It was introduced in IE4 and is supported by all browsers:
$(‘#container’)[0].getBoundingClientRect().width;

For more info: Do not round .width() in jQuery

Css Website development » Search Results » ajax

Do not round .width() in jQuery

Share this post:

Related Posts

Leave a Comment