jquery
  1. jquery-offset

jQuery offset()

The jQuery offset() method is used to retrieve or set the current position of an element relative to the document. It returns an object containing the top and left positions of the element. This method does not affect the position of the element, but merely retrieves its position.

Syntax

Here is the syntax for using the offset() method:

$(selector).offset()

To set the position of an element using offset(), you can also pass an object with top and left properties:

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

Use

The offset() method is commonly used to position elements dynamically on a webpage. By retrieving the current position of an element, you can use the returned values to calculate the new position of that element based on user interactions, screen sizes, or other factors.

Example

Here is an example of using offset() to retrieve the position of an element:

<!DOCTYPE html>
<html>
<head>
    <title>jQuery offset() Example</title>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <style>
        body {
            height: 100px;
        }
        #box {
            width: 100px;
            height: 100px;
            background-color: red;
            position: absolute;
            top: 100px;
            left: 200px;
        }
        p {
            margin-top: 120px;
        }
    </style>
</head>
<body>
    <div id="box"></div>
    <p>Scroll down to see position of box:</p>
    <p id="offset"></p>

    <script>
        var offset = $("#box").offset();
        $("#offset").html("The top position of the box is: " + offset.top + " and the left position is: " + offset.left);
    </script>
</body>
</html>
Try Playground

In this example, we use the offset() method to retrieve the top and left positions of a red box element that is positioned 200px from the top and 200px from the left of the document. We then use JavaScript to display the position of the box on the page.

Summary

The offset() method in jQuery is a useful tool for retrieving or setting the position of an element relative to the document. It can be used in a variety of situations where dynamic positioning of elements is required. Try it out for your next web development project!

Published on: