jQuery outerWidth() example

jQuery outerWidth() function is used to get the current computed outer width (including padding, border, and optionally margin) for the first element in the set of matched elements or sets the outer width of every matched element.

Example 1 - Get the outerWidth of a paragraph

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>outerWidth demo</title>
    <style>
        p {
            margin: 10px;
            padding: 5px;
            border: 2px solid #666;
        }
    </style>
    <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
</head>

<body>

    <p>Hello</p>
    <p></p>

    <script>
        var p = $("p").first();
        $("p").last().text(
            "outerWidth:" + p.outerWidth() +
            " , outerWidth( true ):" + p.outerWidth(true));
    </script>

</body>

</html>
Try it Yourself - Copy paste code in Online HTML Editor to see the result

Example 2 - Change the outer width of each div

Change the outer width of each div the first time it is clicked (and change its color).
<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>outerWidth demo</title>
    <style>
        div {
            width: 60px;
            padding: 10px;
            height: 50px;
            float: left;
            margin: 5px;
            background: red;
            cursor: pointer;
        }

        .mod {
            background: blue;
            cursor: default;
        }
    </style>
    <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
</head>

<body>

    <div>demo</div>
    <div>demo</div>
    <div>demo</div>
    <div>demo</div>
    <div>demo</div>

    <script>
        var modWidth = 60;
        $("div").one("click", function() {
            $(this).outerWidth(modWidth).addClass("mod");
            modWidth -= 8;
        });
    </script>

</body>

</html>
Try it Yourself - Copy paste code in Online HTML Editor to see the result

Comments