Open In App

jQuery offset() Method

The offset() method is an inbuilt method in jQuery which is used to set or returns the offset coordinates of the selected element.
Syntax:  

$(selector).offset()

$(selector).offset({top:value, left:value})

$(selector).offset( function(index, offset) )

Return Value: This method returns the co-ordinate of matched elements.
Below examples illustrate the offset() method in jQuery:
Example 1: In the code below this will return the co-ordinate of the first matched element. 






<!DOCTYPE html>
<html>
 
<head>
    <title>The offset Method</title>
    <script src=
    </script>
 
    <!-- jQuery code to show the working of this method -->
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                let Geek = $("p").offset();
                alert("Top coordinate: " + Geek.top +
                    "   Left Coordinate: " + Geek.left);
            });
        });
    </script>
    <style>
        body {
            display: flex;
            justify-content: center;
        }
 
        div {
            width: 40%;
            min-height: 150px;
            padding: 20px;
            font-size: 25px;
            border: 2px solid green;
            font-weight: bold;
            color: green;
 
        }
    </style>
</head>
 
<body>
    <!-- Click on paragraph -->
    <div>
 
        <p>Welcome to GeeksforGeeks!</p>
 
        <button>click Here!</button>
    </div>
</body>
 
</html>

Output: 



Example 2: Here is the example of jQuery offset() method.




<!DOCTYPE html>
<html>
 
<head>
    <title>The offset Method</title>
    <script src=
    </script>
 
    <!-- jQuery code to show the working of this method -->
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $("p").offset({ top: 100, left: 140 });
            });
        });
    </script>
    <style>
        div {
            width: 300px;
            min-height: 100px;
            color: green;
            font-weight: bold;
            padding: 20px;
            font-size: 25px;
            border: 2px solid green;
        }
    </style>
</head>
 
<body>
    <div>
        <!-- Click on paragraph -->
        <p>Welcome to GeeksforGeeks!</p>
 
        <button>Click Here!</button>
    </div>
</body>
 
</html>

Output: 


Article Tags :