jQuery offset()

Introduction

Return the offset coordinates 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>/*from   w  ww  . j  av  a  2  s .com*/
<script>
$(document).ready(function(){
  $("button").click(function(){
    let x = $("p").offset();
    document.getElementById("demo").innerHTML = "Top: " + x.top + " Left: " + x.left;
  });
});
</script>
</head>
<body>

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

<button>Return the offset coordinates of the p element</button>

</body>
</html>

The offset() method set or gets the offset coordinates for the selected elements relative to the document.

As getter, the offset() method returns the offset coordinates of the first matched element.

It returns an object with 2 properties: top and left.

As setter, this method sets the offset coordinates of all matched elements.

Return the offset coordinates:

$(selector).offset()

Set the offset coordinates:

$(selector).offset({top:value,left:value})

Set offset coordinates using a function:

$(selector).offset(function(index,currentoffset))
Parameter
Optional
Description
{top:value,
left:value}



Required




when setting the offset.
Specifies the top and left coordinates in pixels.
Possible values:
Name/Value pairs, like {top:100,left:100}
An object with top and left properties
function(index,currentoffset)


Optional.


sets a function that returns an object containing the top and left coordinates
index - the index position of the element in the set
currentoffset - the current coordinates of the selected element



PreviousNext

Related