jQuery position()

The jQuery position () method is the same as the jQuery offset() in the sense that it is also used to retrieve the current position of an element. The only difference and the main difference between these two methods is:

The jQuery position() method is used to retrieve the current position of an element relative to the parent element, while the jQuery offset() method is used to retrieve the current position of an element relative to the document.

The jQuery position() method returns the value of the top and left position in pixels. This method is especially useful for positioning a new element near another one.

Syntax:

$(selector).position()

Example:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(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; border-radius:120px}
</style>
</head>
<body>
<p>Click on any circle</p>
<span id="lresult"> </span>
<span id="tresult"> </span>
<div style="background-color:turquoise"></div>
<div style="background-color:cyan"></div>
<div style="background-color:blue"></div>
<div style="background-color:skyblue"></div>
</body>
</html>
Please follow and like us:
Content Protection by DMCA.com