Find Height and Width of Elements using jQuery

Leave a Comment

jQuery provides .height() and .width() functions to find the height and width of page elements.

Height and width of browser window

If you want to retrieve the height and width of the browser window (often referred to as the viewport), use the $(window) selector and the height() and width() functions like this:
var winH = $(window).height();
var winW = $(window).width();

Height and width of the document

To find the width and height for the document, use the $(document) selector and the height() and width() functions:
var docH = $(document).height();
var docW = $(document).width();

To understand how this works, let’s look at some simple CSS for a <div> tag:
div {
width : 300px;
height : 300px;
padding : 20px;
border : 10px solid black;
}

Using width() and height() functions return the CSS width and height of the element.

For example, say your page has the CSS style listed above, and a <div> tag on it:
var divW = $('div').width(); // 300
var divH = $('div').height(); // 300

In below code, innerWidth() returns the width + the left and right padding; innerHeight() returns the CSS height + top and bottom padding:
var divW = $('div').innerWidth(); // 340
var divH = $('div').innerHeight(); // 340

In the code above, the variables divW and divH hold the value 340—the height and width set in the CSS + the padding values on either side.

0 comments:

Post a Comment