I recently ran into a problem with jQuery’s width(). The problem is an item that is hidden with display:none will return a value of 0 instead of its’ actual calculated width. After messing around with it for a little bit I finally came up with a solution. The method I used involved adding some CSS properties to the hidden element. The CSS properties involved are position, visibility, and display.
$HiddenItem.css({
position: "absolute",
visibility: "hidden",
display: "block"
})
$HiddenItem.width();
$HiddenItem.css({
position: "",
visibility: "",
display: ""
})
After setting the above CSS properties on the element, you can then call width() and the correct value will be returned. After you call the width() method you should clear the properties in order to return the element to the way it was.
Setting the properties to an empty string is probably not the best way to do it though. What if there was a position value already set? Using this method would clear out that initial values of the CSS properties.
I found the swap() method to be handy in this situation. I found this method while looking through the jQuery source code.
// A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback ) { var old = {}; // Remember the old values, and insert the new ones for ( var name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } callback.call( elem ); // Revert the old values for ( var name in options ) elem.style[ name ] = old[ name ]; } }By using the swap method, the old CSS properties will be remembered and reapplied after finding the width of the element.
The swap method takes in 3 parameters:
- The element that you would like to swap the CSS properties on
- CSS key/value pairs that you want to change
- A callback function to call after the properties are set
To rewrite the above to use the swap method I would do the following:
var props = { position: "absolute", visibility: "hidden", display: "block" }; var hiddenItemWidth = 0; $.swap($HiddenItem, props, function(){ hiddenItemWidth = $HiddenItem.width(); }); //Use hiddenItemWidth$HiddenItem.width();