Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if element has 'auto' height

Both window.getComputedStyle(element).height and element.clientHeight are returning the current height of the element in pixels, regardless of the value set in the CSS.

Is there any way to find out if the height was set to auto, or other units than pixels ?


One solution that @pvnarula suggests through the page he linked is to temporarily change the contents of the element, then compare heights. A little bit hacky...

like image 438
nice ass Avatar asked Jun 11 '13 12:06

nice ass


1 Answers

Starting by Oriadam answer I created following jQuery function:

/**
* Checks if the element has explicitly set height by CSS styles.
* E.g.:
* 
*      var $myElement = jQuery('.my-element');
*      if ($myElement.hasExplicitHeight()) {
*          //...
*      }
* 
* This function is needed as .height() or .css('height') return a value, even 
* if no height property was explicitly set using CSS. 
* 
* @returns {Boolean}
*/
jQuery.fn.hasExplicitHeight = function() {
    var $element = jQuery(this);
    var $clone = $element.clone();
    $clone.html('');
    $clone.css('visibility', 'hidden');
    $clone.css('position', 'absolute');
    $clone.insertAfter($element);
    var hasExplicitHeight = $element.css('height') === $clone.css('height');
    $clone.remove();
    return hasExplicitHeight;
};

It works fine under condition that it is called only after the document is ready:

jQuery(function() { 
    // this code is launched only after the document is ready
    jQuery('.my-element').hasExplicitHeight();
});
like image 60
Mojo Avatar answered Sep 29 '22 11:09

Mojo