Posted on January 21, 2013 by Chris Harrington

jQuery, widths and hidden elements

I’ve recently been doing some front-end work which involves modifying widths of DOM elements using jQuery. The standard method of modifying the width of an element is as such:

$("some sort of fancy selector").width(100);

As of jQuery 1.8, users are now able to set the outer width, which is defined as the width of the element plus any padding and borders. An optional flag allows you to set the width including margins, too, but only for the getter.

$("fancypants selector").outerWidth(100);

If, however, you need to read the width of an element that’s hidden, jQuery will calculate the width of a hidden element to zero in every case. This makes sense, as the element is hidden and taking up no room on the page. It’s kind of a pain in the ass, though, as in my case, I needed the current width of the element to calculate what the width should be. A handy trick for solving this problem is to set the display’s opacity to some small amount, showing it, then measuring the width. Afterwards, the element can be hidden and its opacity restored to 100%.

var element = $("a hidden element");
var width = element.width(); // this will be zero.
element.css("opacity", "0.01").show();
width = element.width(); // this will now contain the correct width of the element.
element.hide().css("opacity", "1");

If your hidden element is floated and affects the position of surrounding elements, showing it will obviously move those other elements around the page as you’re calculating the width. This isn’t a problem if your hidden element is in an area of the page where it doesn’t matter if it’s shown and taking up space. If your elements are absolutely positioned, you can get around this caveat by moving them off the edge of the screen to calculate the width.

var element = $("another hidden element");
element.css({ left: "-9999px", top: "-9999px" }).show();
var width = element.width();

These are definitely hacks, but when you need widths of hidden elements, they work in a pinch.

gisonline-me-gray