jQuery position()

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

jQuery position()

The jQuery position () method makes you able to retrieve the current position of an element relative to the parent element. It returns the position of the first matched element. This method returns the object with two properties: top and left position in pixels.

The jQuery position() method is different from jQuery offset() method because the position() method retrieves the current position of an element relative to the parent element while the offset() method retrieves the current position relative to the document.

The position() method is more useful when you want to position a new element near another one within the same containing DOM element.

Syntax:

  1. $(selector).position()   

Example of jQuery position() method

Let's take an example to demonstrate the jQuery position() method.

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>  
  5. <script>  
  6. $(document).ready(function(){  
  7.     $("button").click(function(){  
  8.         var x = $("p").position();  
  9.         alert("Top position: " + x.top + " Left position: " + x.left);  
  10.     });  
  11. });  
  12. </script>  
  13. </head>  
  14. <body>  
  15. <p>You are reading this tutorial on javatpoint.com</p>  
  16. <button>Click here to return the offset coordinates of the p element</button>  
  17. </body>  
  18. </html>  

Test it Now

Another example of jQuery position()

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4. <title>The jQuery Example</title>  
  5. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>  
  6. <script type="text/javascript" language="javascript">  
  7. $(document).ready(function() {  
  8. $("div").click(function () {  
  9. var position = $(this).position();  
  10. $("#lresult").html("left position: <span>" + position.left + "</span>.");  
  11. $("#tresult").html("top position: <span>" + position.top + "</span>.");  
  12. });  
  13. });  
  14. </script>  
  15. <style>  
  16. div { width:60px; height:60px; margin:5px; float:left; }  
  17. </style>  
  18. </head>  
  19. <body>  
  20. <p>Click on any square:</p>  
  21. <span id="lresult"> </span>  
  22. <span id="tresult"> </span>  
  23. <div  style="background-color:#ffd700"></div>  
  24. <div  style="background-color:#030303"></div>  
  25. <div  style="background-color:#473c8b"></div>  
  26. <div  style="background-color:#ee82ee"></div>  
  27. </body>  
  28. </html>  

Test it Now