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.

Note
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.
Note
The position() method is more useful when you want to position a new element near another one within the same containing DOM element.

Syntax:

snippet
$(selector).position()

Example of jQuery position() method

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

snippet
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        var x = $("p").position();
        alert("Top position: " + x.top + " Left position: " + x.left);
    });
});
</script>
</head>
<body>
<p>You are reading this tutorial on rookienerd.com</p>
<button>Click here to return the offset coordinates of the p element</button>
</body>
</html>

Another example of jQuery position()

snippet
<!DOCTYPE html>
<html>
<head>
<title>The jQuery Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("div").click(function () {
var position = $(this).position();
$("#lresult").html("left position: <span>" + position.left + "</span>.");
$("#tresult").html("top position: <span>" + position.top + "</span>.");
});
});
</script>
<style>
div { width:60px; height:60px; margin:5px; float:left; }
</style>
</head>
<body>
<p>Click on any square:</p>
<span id="lresult"> </span>
<span id="tresult"> </span>
<div  style="background-color:#ffd700"></div>
<div  style="background-color:#030303"></div>
<div  style="background-color:#473c8b"></div>
<div  style="background-color:#ee82ee"></div>
</body>
</html>
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +