Tuesday, January 15, 2013

How to calculate width of the first matched element using jQuery?

To calculate width of the first matched element or window or document we can make use of the ".width()" method of jQuery.

We can also calculate width using ".css('width')" method of jQuery. Difference between .css('width') and .width() is, ".css('width')" will return a value with units appended to it (for example, 667px) while ".width()" will return a unit-less pixel value (for example, 667).

Now question is when to use which method? It is recommended to use ".width()" method when the calculated width needs to be used in a mathematical calculation.

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

Get width of element using "width()" method:

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

Example:

<!DOCTYPE html>
<html>
<head>
<style>
  body {background:#F1F1A8;} 
  .divContainer{width:550px;border:2px red solid;}
  p{width:530px;border:2px red solid;}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){ 
  $("p").append($("p").width()+" px");
  $("div.divContainer").append($("div.divContainer").width()+" px");
  $("div.document").append($(document).width()+" px");
  $("div.window").append($(window).width()+" px");       
});
</script>
</head>
<body>
<div>
  <div class="document">Width of this document is: </div>
  <div class="window">Width of this window is: </div>
  <div class="divContainer">Width of this div container is: </div>
  <p>Width of this paragraph is: </p>   
</div>
</body>
</html>

Sample output:


How to calculate width of the first matched element using jQuery


Demo:



0 comments:

Post a Comment

Subscribe via Email