views:

46

answers:

4

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?

A: 

I am not quite sure if I am answering your question correctly, but if you use the width() function this will give you an integer representing the rendered width in pixels.

Giles
Yes, the problem it does that even if there's no width explicitly specified in the CSS for the element. <div style="width: auto"></div> will return an integer value. I want it to return "auto" (or to find a way to tell whether it's auto or not).
Zurahn
This is a tough question, because even using `$('element').css("width");` seems to always return a pixel width value for an object. Even if it's set to 100%. This is essentially the same as using the getComputedStyle suggested in the first answer.
Nilloc
+1  A: 

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:

Ionuț G. Stan
A: 
  1. create function
  2. pass css element id to function
  3. write a case where statement to be performed on the width property of the element id

NOTE: to use on mulitple elements would be wise to use a loop with an array of element names

elitepraetorian
A: 

$('#test')[0].style.width=="auto" should work: http://jsfiddle.net/KxTLE/ and http://jsfiddle.net/KxTLE/1/ Try

jQuery.fn.isAuto=function() {
if(this[0]) {
    var ele=$(this[0]);
    if(this[0].style.width=='auto' || ele.outerWidth()==$('#s').parent().width()) {
        return true;
    } else {
        return false;
    }
}
return undefined;
};

And example: http://jsfiddle.net/KxTLE/6/

Alex Nolan
Nice concept, but this.style is limited strictly to inline styles. I guess I didn't specify, but that's obviously going to be a bit of a problem. Though by the looks of it, there's going to be a problem no matter what.
Zurahn