jQuery position()

Introduction

Return the top and left position of a <p> element:

View in separate window

<!DOCTYPE html>
<html>
<head>
<script 
 src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>/*w ww .j a va2 s.c om*/
<script>
$(document).ready(function(){
  $("button").click(function(){
    let x = $("p").position();
    document.getElementById("demo").innerHTML = 
             "Top position: " + x.top + " Left position: " + x.left;
  });
});
</script>
</head>
<body>

<p id="demo"></p>
<p>This is a paragraph.</p>
<button>test</button>

</body>
</html>

The position() method returns the position relative to its parent element of the first matched element.

This method returns an object with 2 properties: the top and left positions in pixels.

$(selector).position()



PreviousNext

Related