How to make jQuery to not round value returned by .width()?
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).
Solution 1:
Use the native Element.getBoundingClientRect
rather than the style of the element. It was introduced in IE4 and is supported by all browsers:
$("#container")[0].getBoundingClientRect().width
Note: For IE8 and below, see the "Browser Compatibility" notes in the MDN docs.
$("#log").html(
$("#container")[0].getBoundingClientRect().width
);
#container {
background: blue;
width: 543.5px;
height: 20px;
margin: 0;
padding: 0;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container"></div>
<p id="log"></p>
Solution 2:
Ross Allen's answer is a good starting point but using getBoundingClientRect().width will also include the padding and the border width which ain't the case the the jquery's width function:
The returned TextRectangle object includes the padding, scrollbar, and the border, but excludes the margin. In Internet Explorer, the coordinates of the bounding rectangle include the top and left borders of the client area.
If your intent is to get the width
value with the precision, you'll have to remove the padding and the border like this:
var a = $("#container");
var width = a[0].getBoundingClientRect().width;
//Remove the padding width (assumming padding are px values)
width -= (parseInt(a.css("padding-left")) + parseInt(a.css("padding-right")));
//Remove the border width
width -= (a.outerWidth(false) - a.innerWidth());