How to get the actual width of an element in jQuery, even with border-box: box-sizing
This article was originally published at https://gist.github.com/joepie91/5ffffefbf24dcfdb4477.
This is ridiculous, but per the jQuery documentation:
Note that
.width()
will always return the content width, regardless of the value of the CSSbox-sizing
property. As of jQuery 1.8, this may require retrieving the CSS width plusbox-sizing
property and then subtracting any potential border and padding on each element when the element hasbox-sizing: border-box
. To avoid this penalty, use.css( "width" )
rather than.width()
.
function parsePx(input) {
let match;
if (match = /^([0-9+])px$/.exec(input)) {
return parseFloat(match[1]);
} else {
throw new Error("Value is not in pixels!");
}
}
$.prototype.actualWidth = function() {
/* WTF, jQuery? */
let isBorderBox = (this.css("box-sizing") === "border-box");
let width = this.width();
if (isBorderBox) {
width = width
+ parsePx(this.css("padding-left"))
+ parsePx(this.css("padding-right"))
+ parsePx(this.css("border-left-width"))
+ parsePx(this.css("border-right-width"));
}
return width;
}