jQuery width()

jQuery width() method sets or returns the width of the selected element.

Syntax:

When used to return the width:

$(selector).width()

When used to set the width:

$(selector).width(value)

When used to set the width using a function:

$(selector).width(function(index,currentwidth))

Value:

  • Value is a compulsory parameter of the jQuery width() method, as it specifies the width to set in px, em, pt, etc.
Function:
  • It is an optional parameter.
  • The function parameter is used to return the new width of the selected element.
Index:
  • The index is an argument passed within the function.
  • It is used to give an index position to an element in the set.
Currentwidth:
  • This parameter returns the current width of the selected element.

Example1:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert("Width: " + $("div").width());
});
});
</script>
</head>
<body>
<div style="height:100px;width:500px;padding:10px;margin:3px;border:1px solid blue;background-color:lightpink;"></div><br>
<button>Width</button>
</body>
</html>

Example2:

<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 100px;
height: 80px;
float: left;
margin: 5px;
background:orange;
cursor: pointer;
}
.mod {
background: turquoise;
cursor: default;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div>Thick</div>
<div>Thin</div>
<div>Thinner</div>
<div>Thinnest</div>
<script>
var modWidth = 70;
$( "div" ).one( "click", function() {
$( this ).width( modWidth ).addClass( "mod" );
modWidth -= 10;
});
</script>
</body>
</html>