jQuery width() Method
You are Here:
jQuery width() Method
The jQuery width()
method gets or sets the width of the selected elements.
Get Width
In the following example, we will get the width of the div container.
Example
HTML Editor
<!DOCTYPE html>
<html lang="en-US">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
div{
border: 2px solid black;
height: 100px;
width: 100px;
}
</style>
</head>
<body>
<h1>jQuery width() Method</h1>
<div></div>
<p>Click on the button to find the width of div.</p>
<button>Click Me</button>
<script>
$(document).ready(function(){
$("button").click(function(){
alert($("div").width());
});
});
</script>
</body>
</html>
Syntax
// To get width
$(selector).width();
//To set width
$(selector).width(integer)
//To callback
$(selector).width(function(index, width));
Parameter Values
Value | Type | Explanation |
---|---|---|
integer | Optional | Specifies the width in px. |
function(index, width) | Optional | Specifies a function that returns the new width of selected elements Parameters Explanation
|
Set Width
In the following example, we will set the width of the div container to 200px.
Example
HTML Editor
<!DOCTYPE html>
<html lang="en-US">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
div{
border: 2px solid black;
height: 100px;
width: 100px;
}
</style>
</head>
<body>
<h1>jQuery width() Method</h1>
<div></div>
<p>Click on the button to set div's width to 200px.</p>
<button>Click Me</button>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").width(200);
});
});
</script>
</body>
</html>
Set Width with Callback
In the following example, we will set the width of the two div containers using a callback.
Example
HTML Editor
<!DOCTYPE html>
<html lang="en-US">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
div{
border: 1px solid black;
width: 100px;
height: 50px;
margin: 10px;
}
</style>
</head>
<body>
<h1>jQuery width() Method</h1>
<div>Child 1</div>
<div>Child 2</div>
<p>Click on the button to change the first div's width to 100px and second div's width to 150px.</p>
<button>Click Me</button>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").width(function(index, myWidth){
$("div").eq(index).width(myWidth * (index + 2));
});
});
});
</script>
</body>
</html>
Reminder
Hi Developers, we almost covered 99.5% of jQuery Tutorials with examples for quick and easy learning.
We are working to cover every Single Concept in jQuery.
Please do google search for:
Join Our Channel
Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.
This channel is primarily useful for Full Stack Web Developer.