How to Use JQuery Position With Example?

The jQuery position () method enables you to get the current event of an element relative to the parent element. It returns the event of the first matched element. In this method, the object has two properties. Which represent the top and left positions in pixels.

The jQuery position () method does not support the retrieval of event elements coordinates in JQuery or accounting of the margin set on the html document element. This only applies to visible elements. This means that you can get the position of elements with visibility. Hidden, but not with display.

Syntax:-

$(selector).position()

Example Code

<!DOCTYPE html>
<html>
<head>
<title>The position Method</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
var x = $("p").position();
alert("Top position: " + x.top);
});
});
</script>
<style>
div {
font-weight: bold;
padding:20px;
font-size: 30px;
border: 3px solid red;
width: 300px;
height: 150px;
}
</style>
</head>
<body>
<div>
<p>Experts PHP Examples.</p>
<button>Click Here!</button>
</div>
</body>
</html>

The jQuery position () method allows us to recover the current event of an element, especially its margin box, relative to the offset parent. Event () is more useful when the second element has a new element and DOM element in it.