jQuery outerWidth: Main Tips
- jQuery
.outerWidth()
gets the outer width of the first element of matched elements in pixels. - You can also use jQuery
.outerWidth()
to set a new width for every specified element. - To ensure the results are correct, only use this method on visible elements.
- jQuery height and width methods are also explained in this tutorial.
Meaning and Usage of .outerWidth()
The .outerWidth()
jQuery method is used to set or return the outer width of the selected elements. It includes both borders and padding. You can make it include the margin as well.
In the example below, clicking a button triggers an alert box. It displays the current outer width of the element. Close the alert to change it to 100
:
$("button").click(() => {
alert($("p").outerWidth());
});
$("button").click(() => {
$("p").outerWidth(100);
});
Note: the .outerWidth() jQuery method does not work on window and document objects.
To return the width, you need to use this syntax:
$(selector).outerWidth(margin);
Note: if the element is empty, function returns undefined.
The optional margin
parameter defines whether the .outerWidth()
jQuery will include margin. It has a boolean value (false
by default).
To set the width, specify the new width in a string, number, or a function returning the needed value:
$(selector).outerWidth(newWidth);
Note: if you only define the new width in a number (no unit specified), jQuery takes it as a number of pixels.