Pin It
Pages Menu
Categories Menu

Posted by on May 23, 2013 in jQuery Resources & Tutorials | 0 comments

jQuery: How to Find the Dimensions of an Element

jQuery: How to Find the Dimensions of an Element

You can apply jQuery’s height and width methods to any kind of element for figuring out the height and width of an element. But height and width methods are not all to figure out the sizes and they fall short if you want to get exact space of an element. For this purpose, jQuery also provides methods like innerWidth, outerWidth, innerHeight and outHeight.

What above mentioned functions do? the functions with inner term returns height & width including the padding and excluding the border, and the functions with outer terms returns including both the padding and the border.

Below is the example HTML mockup:

[code type=”php”]
<div id=”all_the_results”></div>
<div id=”custom_div”>Your text goes here.</div>

For styling purpose, we need the CSS something like this:

[code type=”php”]
#custom_div { border: 1px; padding: 10px; height: 30px; width: 100px; }

Here is the final jQuery code snippet, don’t worry I’ll discuss the code after.

[code type=”php”]
$(document).ready(function() {
var custom_div      = $(“#custom_div”);
var all_the_results = $(“#all_the_results”);

//Appending Text with different scenarios
//Output will be 100
$(‘<p>Final Width is: ‘ + custom_div.width() + ‘</p>’).appendTo(all_the_results);
//Output will be 30
$(‘<p>Final Height is: ‘ + custom_div.height() + ‘</p>’).appendTo(all_the_results);
//Output will be 120
$(‘<p>Final Inner width: ‘ + custom_div.innerWidth() + ‘</p>’).appendTo(all_the_results);
//Output will be 50
$(‘<p>Final Inner height: ‘ + custom_div.innerHeight() + ‘</p>’).appendTo(all_the_results);
//Output will be 122
$(‘<p>Final Outer width: ‘ + custom_div.outerWidth() + ‘</p>’).appendTo(all_the_results);
//Out will be 52
$(‘<p>Final Outer height: ‘ + custom_div.outerHeight() + ‘</p>’).appendTo(all_the_results);

Demo of the example

The basic height and width functions are limited to use when you’re attempting to calculate the actual size that an element with padding & border captures on the screen. So outerWidth/outerHeight & innerWidth/innerHeight are the best choice for calculating the actual dimensions that you’re after.

Post a Reply

Your email address will not be published. Required fields are marked *