Wednesday, January 30, 2013

How to set width to any element using jQuery?

To set width to any element we can make use of the ".width(value)" method of jQuery. Where  "value" can be any integerrepresenting the number of pixels (for example, 60) or an integer  with unit of measurement appended to it (for example, 60px or 60% or auto).

1. How to calculate width of the first matched element using jQuery?
2. How to set width to any element using jQuery?(this article)

Set width to element using "width()" method:

$(document).ready(function(){   
$("div.one").width(400).append("Width of this container is :"+$("div.one").width()+" px");
$("div.two").width(425).append("Width of this container is :"+$("div.two").width()+" px");
$("div.three").width(450).append("Width of this container is :"+$("div.three").width()+" px");
});

Example:

<!DOCTYPE html>
<html>
<head>
<style> 
  body {background:#F1F1A8;}   
  div {height:50px;background:red;margin:5px;} 
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){   
$("div.one").width(400).append("Width of this container is :"+$("div.one").width()+" px");
$("div.two").width(425).append("Width of this container is :"+$("div.two").width()+" px");
$("div.three").width(450).append("Width of this container is :"+$("div.three").width()+" px");
});
</script>
</head>
<body>
  <div class="one"></div>
  <div class="two"></div>
  <div class="three"></div>
</body>
</html>

Sample Output:


How to set width to any element using jQuery

Demo:



0 comments:

Post a Comment

Subscribe via Email