Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 703
Elle H Avatar asked Aug 24 '10 14:08

Elle H


People also ask

How can check window width using jQuery?

The . width() method is recommended when an element's width needs to be used in a mathematical calculation. This method is also able to find the width of the window and document. $( document ).

How do you find the width of a DOM element?

Use offsetWidth & offsetHeight properties of the DOM element to get its the width and height.


2 Answers

This will get either string "auto" or "180px" on absolute values.

$('element').prop('style').width

for width or

$('element').prop('style').height

for height.

like image 74
prdatur Avatar answered Oct 11 '22 16:10

prdatur


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:

  • http://msdn.microsoft.com/en-us/library/ms535231(VS.85).aspx
  • https://developer.mozilla.org/en/DOM:window.getComputedStyle
  • https://developer.mozilla.org/en/CSS/computed_value
like image 9
Ionuț G. Stan Avatar answered Oct 11 '22 15:10

Ionuț G. Stan