I'm trying to calculate the width of an element which has a hidden parent. Because the element is not visible, it returns a zero width. So I wrote this little function:
/**
* Compute the width of an element if it were to be visible.
*
* $element: The element you want to compute the width of
* $hiddenParent: A parent (ancestor) of $element which is currently hidden
*
* Returns: the width of $element if it were to be visible.
*/
var getDisplayedWidth = function($element, $hiddenParent) {
var oldDisplay = $hiddenParent.css("display");
$hiddenParent.show();
var displayedWidth = $element.width();
$hiddenParent.css("display",oldDisplay);
return displayedWidth;
};
It works and returns the displayed width. But the problem is, the value of "oldDisplay" is not the real old value of the inline display property. It's the calculated value of the display property. (this is not a bug - it's totally what I would expect based on jQuery's documentation.)
This slight difference means that the method breaks down in the following use case - we have an element that is initially display:none but that is controlled through a class rather than an inline style. So oldDisplay gets set to "none". Now, when the display gets put back, the display:none becomes an inline style. Later in the execution, when some other javascript adds a class to make it visible, the inline style takes precedence and the element does not appear.
What I really want to do in this case is extract only the inline style version of the "display" property. If the element has no inline "display" property (as in the above example) then I want oldDisplay to be set to an empty string.
Now I've explained the background, the question simply put is this - how do I get a CSS property only from inline styles?
(PS: I know that I could do this by manually parsing the "style" attribute. But I feel there must be a better way, especially using jQuery.)
display: nonebecomes an inline style?oldDisplaygets set to "none". So when I set$hiddenParent.css("display", "none");, this sets an inline style.