Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Get height of hidden element in jQuery

I need to get height of an element that is within a div that is hidden. Right now I show the div, get the height, and hide the parent div. This seems a bit silly. Is there a better way?

I'm using jQuery 1.4.2:

$select.show(); optionHeight = $firstOption.height(); //we can only get height if its visible $select.hide(); 
like image 309
mkoryak Avatar asked Feb 27 '10 00:02

mkoryak


People also ask

How to get hidden div height in jQuery?

css({'position':'absolute', 'visibility':'hidden', 'display':'block'}); var divHeight = $('#hidden_div'). outerHeight(true); // outerHeight includes the paddings and borders. setting the optional value to true, includes the div's margins as well.

Does display none have height?

Does display none have height? As mentioned in the first difference, an element with display: none doesn't take any space on the page. Hence, all properties related to the element size, such as clientHeight , clientWidth , height , offsetHeight , offsetWidth , scrollHeight , scrollWidth and width are zero.

What is height in jQuery?

In jQuery, height method is used to get the height of any element in HTML. The height method sets and returns the height of the HTML elements. Method 1: The height() method returns the first matched element's height, But the height(value) method sets all matched elements height.

Can jQuery find hidden elements?

You can simply use the jQuery :visible or :hidden selector to select all the visible or hidden elements in an HTML page. The jQuery :visible selector considered an element visible if they consume space in the document.


2 Answers

You could do something like this, a bit hacky though, forget position if it's already absolute:

var previousCss  = $("#myDiv").attr("style");  $("#myDiv").css({     position:   'absolute', // Optional if #myDiv is already absolute     visibility: 'hidden',     display:    'block' });  optionHeight = $("#myDiv").height();  $("#myDiv").attr("style", previousCss ? previousCss : ""); 
like image 174
Nick Craver Avatar answered Oct 27 '22 01:10

Nick Craver


I ran into the same problem with getting hidden element width, so I wrote this plugin call jQuery Actual to fix it. Instead of using

$('#some-element').height(); 

use

$('#some-element').actual('height'); 

will give you the right value for hidden element or element has a hidden parent.

Full documentation please see here. There is also a demo include in the page.

Hope this help :)

like image 23
ben Avatar answered Oct 26 '22 23:10

ben