jQuery width

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

ParameterDescription
ValueIt 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:


  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3. <head>  
  4.   <meta charset="utf-8">  
  5.   <title>width demo</title>  
  6.   <style>  
  7.   div {  
  8.     width: 100px;  
  9.     height: 80px;  
  10.     float: left;  
  11.     margin: 5px;  
  12.     background:orange;  
  13.     cursor: pointer;  
  14.   }  
  15.   .mod {  
  16.     background: green;  
  17.     cursor: default;  
  18.   }  
  19.   </style>  
  20.   <script src="https://code.jquery.com/jquery-1.10.2.js"></script>  
  21. </head>  
  22. <body>  
  23. <div>A</div>  
  24. <div>B</div>  
  25. <div>C</div>  
  26. <div>D</div>  
  27. <div>E</div>  
  28. <script>  
  29. var modWidth = 70;  
  30. $( "div" ).one( "click", function() {  
  31.   $( this ).width( modWidth ).addClass( "mod" );  
  32.   modWidth -= 10;  
  33. });  
  34. </script>  
  35. </body>  
  36. </html> 

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *