
- jQuery - Home
- jQuery - Roadmap
- jQuery - Overview
- jQuery - Basics
- jQuery - Syntax
- jQuery - Selectors
- jQuery - Events
- jQuery - Attributes
- jQuery - AJAX
- jQuery CSS Manipulation
- jQuery - CSS Classes
- jQuery - Dimensions
- jQuery - CSS Properties
- jQuery Traversing
- jQuery - Traversing
- jQuery - Traversing Ancestors
- jQuery - Traversing Descendants
- jQuery References
- jQuery - Selectors
- jQuery - Events
- jQuery - Effects
- jQuery - HTML/CSS
- jQuery - Traversing
- jQuery - Miscellaneous
- jQuery - Properties
- jQuery - Utilities
- jQuery Plugins
- jQuery - Plugins
- jQuery - PagePiling.js
- jQuery - Flickerplate.js
- jQuery - Multiscroll.js
- jQuery - Slidebar.js
- jQuery - Rowgrid.js
- jQuery - Alertify.js
- jQuery - Progressbar.js
- jQuery - Slideshow.js
- jQuery - Drawsvg.js
- jQuery - Tagsort.js
- jQuery - LogosDistort.js
- jQuery - Filer.js
- jQuery - Whatsnearby.js
- jQuery - Checkout.js
- jQuery - Blockrain.js
- jQuery - Producttour.js
- jQuery - Megadropdown.js
- jQuery - Weather.js
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.