.position() method in Jquery

Description:

The jquery .position() method Get the current coordinates of the first element for the matched elements, relative to the offset parent. This method does not accept any arguments.

Syntax

  • $(selector).position()

When to use?

The .position() method allows us to retrieve the current position of an element relative to the offset parent. It will be more useful if we need to place a new element near another one within the same container . It returns an object containing the top and left properties as shown below

dotnet-helpers-jquery-position-method-thiyagu-jquery-helpers.

Example: 

<html>
<head>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
 <style>
 .defaultClass {
 border: 5px solid #eed5b7;
 padding: 10px;
 width: 50px;
 height: 50px;
 background-color: red;
 display:inline-block;
 }
 
 </style>
 <script type="text/javascript">
 $(document).ready(function () {
 $('.btnClass').click(function () {
 var divBoxDetail = $("#divBoxDetails");
 var position = divBoxDetail.position();
 divBoxDetail.text("left: " + Math.round(position.left) + ", top: " + Math.round(position.top));
 })
 });
 </script>
</head>
<body>
 <button class="btnClass" id="addMethod">GEt Position</button><br/>
 <div id="divbox1" class="defaultClass">
 </div>
 <br /><br />
 <div id="divBoxDetails"></div>
</body>
</html>

Output: 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.