Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to detect implicit vs. explicit CSS height values in jQuery?

In jQuery, both $('#foo').height() and $('#foo').css('height') return a value, even if no height property was explicitly set using CSS. Is there a way to detect if an element doesn't have an explicit height, i.e. it's just being rendered according to its contents?

Here's an example I wrote to demonstrate: http://jsfiddle.net/Enn6p/2/

EDIT

To clarify my question further, $('#foo').css('min-height') and $('#foo').css('max-height') already properly return an empty string if they aren't explicitly set. I am looking for a way to find out whether an explicit height value is being set via CSS, or not.

USE CASE

I have a script that attempts to make floated elements the same height. It does this by looping over the elements to see which one is the tallest, then applying that height to all of them. In some cases, these elements already have an explicit height set, but the others are rendered implicitly.

I now want to add the ability to undo this, and make everything go back to their original heights. In order to do this, I need to know if the element originally had a height set, or if the height was "auto". Once I can do this, I can store the original value in the data collection for the element and then use that to revert to the original height later.

like image 518
Chris Bloom Avatar asked Jun 10 '14 17:06

Chris Bloom


2 Answers

In some old versions of jQuery it was possible:

http://jsfiddle.net/strikernl/y3P3A/

but now you should just use a function like:

function sizeDefined(obj){
   var tmp = obj.clone().html('').appendTo($('body'));
    var w = (tmp.width()==0  ? "no":"yes");
    var h = (tmp.height()==0  ? "no":"yes");
    tmp.remove();
   return  [w,h];
}

http://jsfiddle.net/Enn6p/12/

like image 58
Ashkan Mobayen Khiabani Avatar answered Oct 18 '22 15:10

Ashkan Mobayen Khiabani


Basically, if you get rid of the content of an element and measure its height it will equate to 0, unless it has a height set previously (as a style). So by that reasoning:

 function hasSetHeight(elem){
    var html=elem.html();
    elem.html('');
    height = elem.height();
    elem.html(html);
    return (height > 0);
}

deletes all content of the element, measures its height and returns true or false if the element has a set height or not.

like image 1
theonlygusti Avatar answered Oct 18 '22 15:10

theonlygusti