Open In App

How to validate position in jQuery ?

Last Updated : 29 Jul, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will find how to validate position using jQuery position() method. The .position() method in jQuery returns the position of the first matched element relative to its parent element.

Syntax:

$(selector).position()

Return value:

  • Returns an object containing the properties top and left.

Example: Let us take an example to understand .position() method of jQuery.

HTML
<!DOCTYPE HTML>
<html>
<head>
    <script src=
"https://code.jquery.com/jquery-3.5.0.js">
    </script>
</head>
<body style="text-align:center;">
    <h2 id="heading" style="color:green;">
        GeeksforGeeks
    </h2>
    
<p>
        jQuery | .position() method
    </p>


    <button id="button">
        click here to get position of heading
    </button>
      
    <script>
    // Selecting h2 tag and using .position() method 
    // to find its position relative to offset parent.
     $(document).ready(function(){
      $("button").click(function(){
        var x = $("h2").position();
        $( "p" ).last().text ("Top position is : " + 
               x.top + " Left position is : " + x.left);
      });
    });
    </script>
</body>  
</html>

Output :

jQuery position method

Next Article

Similar Reads