Skip to content
Related Articles

Related Articles

Improve Article

How to increase the width of a div by specified pixels once it is clicked using jQuery ?

  • Last Updated : 27 Jun, 2021

In this article, we will learn how to increase the width of a division by specified pixels once it is clicked using jQuery.

We can do this task using the width() method that is used to return and set the width of an element in JQuery. So when we click on it a function is called in which first we store the current width of the div in a variable using the width() method and then increase specified pixels and set its width using width(value) method in JQuery.

Syntax:

// To return the width of the selected element
$(selector).width()

// To set the width of the selected element
$(selector).width(value)

Example:

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <script src=
    </script>
 
    <style>
        body {
            color: green;
            font-size: 30px;
        }
 
        div {
            font-size: 40px;
            background-color: rgb(190, 190, 190);
            width: 300px;
            border: solid 4px red;
        }
 
        button {
            font-size: 30px;
        }
    </style>
</head>
 
<body>
    <center>
        <h1>GeeksforGeeks</h1>
        <div onclick="fun()">
            Click to Div to increase the width
        </div>
    </center>
 
    <script>
         
        // Width of the div before clicking button
        var w = $("div").width();
 
        // Increment that we want to do
        var inc = 200;
        function fun() {
 
            // Increase width by 200 and set
            $("div").width(w + inc);
        }
    </script>
</body>
 
</html>

Output: 




My Personal Notes arrow_drop_up
Recommended Articles
Page :