Pages

Wednesday 12 June 2013

.height() , jQuery .height()

Get the current computed height for the first element in the set of matched elements or set the height of every matched element.

.height()Returns: Integer

Description: Get the current computed height for the first element in the set of matched elements.
  • version added: 1.0.height()

    • This method does not accept any arguments.
The difference between .css('height') and .height() is that the latter returns a unit-less pixel value (for example, 400) while the former returns a value with units intact (for example, 400px). The .height() method is recommended when an element's height needs to be used in a mathematical calculation.
This method is also able to find the height of the window and document.
1
2


$(window).height(); // returns height of browser viewport




$(document).height(); // returns height of HTML document


Note that .height() will always return the content height, regardless of the value of the CSS box-sizing property. As of jQuery 1.8, this may require retrieving the CSS height plus box-sizing property and then subtracting any potential border and padding on each element when the element has box-sizing: border-box. To avoid this penalty, use .css("height") rather than .height().
Note: Although style and script tags will report a value for .width() or height() when absolutely positioned and given display:block, it is strongly discouraged to call those methods on these tags. In addition to being a bad practice, the results may also prove unreliable.

Example:


Show various heights. Note the values are from the iframe so might be smaller than you expected. The yellow highlight shows the iframe body.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28



<!DOCTYPE html>




<html>




<head>




<style>




body { background:yellow; }




button { font-size:12px; margin:2px; }




p { width:150px; border:1px red solid; }




div { color:red; font-weight:bold; }




</style>




<script src="http://code.jquery.com/jquery-1.9.1.js"></script>




</head>




<body>




<button id="getp">Get Paragraph Height</button>




<button id="getd">Get Document Height</button>




<button id="getw">Get Window Height</button>








<div>&nbsp;</div>




<p>




Sample paragraph to test height




</p>




<script>




function showHeight(ele, h) {




$("div").text("The height for the " + ele +




" is " + h + "px.");




}




$("#getp").click(function () {




showHeight("paragraph", $("p").height());




});




$("#getd").click(function () {




showHeight("document", $(document).height());




});




$("#getw").click(function () {




showHeight("window", $(window).height());




});








</script>








</body>




</html>












No comments:

Post a Comment