Monday, December 24, 2012

How to calculate width of any element including padding using jQuery?

To calculate width of any element including padding we can make use of the ".innerWidth()"
method of jQuery. This method will return width including padding left and padding right.

Note: We cannot use this method to calculate width of window and document, instead we can use ".width()" method.

1. How to calculate width of any element using jQuery?
2. How to calculate width of any element including padding using jQuery?(this article)
3. How to calculate width of any element including padding, border and margin using jQuery?

Calculate width of element using ".innerWidth()" method:

$(document).ready(function(){    
$("div.width").append($("div.width").width()+" px");
$("div.innerWidth").append($("div.innerWidth").innerWidth()+" px"); 
});

Example:

<!DOCTYPE html>
<html>
<head>
<style>
  body {background:#F1F1A8;}
  div {padding:10px;}  
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){     
  $("div.width").append($("div.width").width()+" px");
  $("div.innerWidth").append($("div.innerWidth").innerWidth()+" px");
});
</script>
</head>
<body>
<div>   
<div class="width">Width of this div container without including padding is: </div>  
<div class="innerWidth">width of this div container including padding is: </div>      
</div>
</body>
</html>

Sample Output:


How to calculate width of any element including padding using jQuery


Demo:



2 comments:

  1. This is the best blog for beginners. Thanks for your efforts. It helped me a lot.

    ReplyDelete

Subscribe via Email