jQuery width() method is used to return or set the width of matched element.
To return width: When this method is used to return the width, it returns the width of first matched element.
To set width:When this method is used to set the width, it sets the width for every matched element.
This method is one of a jQuery dimension.
List of jQuery dimension:
- width()
- height()
- innerWidth()
- innerHeight()
- outerWidth()
- outerHeight()
Syntax:
To return the width:
$(selector).width()
To set the width:
$(selector).width(value)
To set the width using a function:
$(selector).width(function(index,currentwidth))
Parameters of jQuery width() method
Parameter | Description |
---|---|
Value | It is a mandatory parameter. It is used for setting width. It specifies the width in px, em, pt etc. The default value of jQuery width() method is px. |
Function(index, currentwidth) | It is an optional parameter. It specifies a function that provides the new width of selected element.Index:IIt provides the index position of the element in the set.currentwidth:It provides the current width of the selected element. |
Example of jQuery width() method
Let’s take an example to demonstrate the effect of jQuery width() method.
To return width:
<!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 of div: " + $("div").width());
});
});
</script>
</head>
<body>
<div style="height:100px;width:200px;padding:10px;margin:3px;border:1px solid blue;background-color:lightpink;"></div><br>
<button>Execute the jQuery width() method to return width</button>
</body>
</html>
jQuery width() example 2
To set width:
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="utf-8">
- <title>width demo</title>
- <style>
- div {
- width: 100px;
- height: 80px;
- float: left;
- margin: 5px;
- background:orange;
- cursor: pointer;
- }
- .mod {
- background: green;
- cursor: default;
- }
- </style>
- <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
- </head>
- <body>
- <div>A</div>
- <div>B</div>
- <div>C</div>
- <div>D</div>
- <div>E</div>
- <script>
- var modWidth = 70;
- $( "div" ).one( "click", function() {
- $( this ).width( modWidth ).addClass( "mod" );
- modWidth -= 10;
- });
- </script>
- </body>
- </html>
Leave a Reply