jQuery innerWidth: Main Tips
- jQuery
.innerWidth()
method sets or retrieves the inner width of the selected element. - Unlike .width(),
innerWidth
jQuery method does not return window or document width. - To learn more about the methods jQuery offers for height and width properties, visit this tutorial.
Using innerWidth Correctly
The .innerWidth()
jQuery method is used to set or return the element's inner width. It includes padding but not borders.
Note: when the element is empty, the method returns undefined.
Take a look at the example below. Click the button to see the inner width of the element displayed in an alert box. By closing it, you make the inner width change:
$("button").click(() => {
alert($("p").innerWidth());
});
$("button").click(() => {
$("p").innerWidth(100);
});
To return the width, the .innerWidth()
jQuery syntax is as follows:
$(selector).innerWidth();
To set the width, include the newWidth
parameter:
$(selector).innerWidth(newWidth);
newWidth
can be defined in a string or a number. In the first case, you can include any valid unit of measurement. If you only add a number, jQuery takes it as pixels by default.
Note: you can also define newWidth in a function that returns a value needed for jQuery innerwidth.