• jQuery Video Tutorials

jQuery position() Method



The position() method in jQuery is used to return the current position of an element relative to its offset parent.

The offset parent is the nearest positioned ancestor element. This method returns an object with 2 properties (of the select element); the top and left positions in pixels.

Syntax

Following is the syntax of position() method in jQuery −

$(selector).position()

Parameters

This method does not accept any parameters.

Example 1

In the following example, we are using the position() method to return the top and left position of a "paragraph" element −

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            $("button").click(function() {
                var pos = $("p").position();
                alert("Top: " + pos.top + ", Left: " + pos.left);
            });
        });
    </script>
</head>
<body>
    <p>Click the button below to fetch the position (top and left)</p>
    <button>Get Position</button>
</body>
</html>

When click the button, it returns the top and left position of a "paragraph" element.

Example 2

Here, we are fetching the position of a <div> element inside a "div" element using the position() method −

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
      $(document).ready(function() {
          $("button").click(function() {
              var pos = $("#inner").position();
              $("p").text("Top: " + pos.top + ", Left: " + pos.left);
          });
      });
  </script>
    <style>
        #container {
            position: relative;
            width: 300px;
            height: 300px;
            border: 1px solid black;
        }
        #inner {
            position: absolute;
            top: 50px;
            left: 50px;
            width: 100px;
            height: 100px;
            background-color: lightblue;
        }
    </style>
</head>
<body>
    <div id="container">
        <div id="inner"></div>
    </div>
    <button>Get Position</button>
    <p></p>
</body>
</html>

When we click the "Get Position" button, it gives the left and top position of the inner "div" element relative to its parent "div" element.

jquery_ref_html.htm
Advertisements