jQuery innerWidth() example

jQuery innerWidth() function is used to get the current computed inner width (including padding but not the border) for the first element in the set of matched elements or sets the inner width of every matched element.

Example 1 - Get the innerWidth of a paragraph.

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

<head>
    <meta charset="utf-8">
    <title>innerWidth 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("innerWidth:" + p.innerWidth());
    </script>

</body>

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

Example 2 - Change the inner width of each div element

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

<head>
    <meta charset="utf-8">
    <title>innerHeight demo</title>
    <style>
        div {
            width: 60px;
            padding: 10px;
            height: 70px;
            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>sourcecodeexamples</div>
    <div>sourcecodeexamples</div>
    <div>sourcecodeexamples</div>
    <div>sourcecodeexamples</div>
    <div>sourcecodeexamples</div>

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

</body>

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

References


Comments