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.
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%.