Search code examples
javascriptjquerycssdomcomputed-style

Detecting width: auto in jQuery


I'm retrieving the width of elements using jQuery and would prefer it if I could have an indication of whether there was an explicit width (and height) specified.

<div id="test"></div>
<script type="text/javascript">
$(function() { alert($('#test').css('width')); });
</script>

This will alert the implicit width of the div in terms of how many pixels it takes up on the client's screen. Is there any way that if the width is either missing or set as width: auto that it can be verified using jQuery?

That is, instead of the above example returning an integer, it would return either auto or undefined. Or, alternatively, is there an equivalent of a isAuto function?


Solution

  • I don't believe it's possible for the moment. At least not in any other browser than IE. IE implements element.currentStyle which represents styles at they were written in the CSS file. On the other hand, the rest of the browsers implement window.getComputedStyle which returns the computed values of those styles. That's what you receive there, a numeric value instead of auto.

    The only way around it would be to parse CSS declarations from document.styleSheets.

    References: