jQuery offset()

The jQuery offset() method sets or returns the offset coordinates of the selected elements.

Syntax:

When used to return the offset coordinates.

$(selector).offset()

When used to set the offset coordinates.

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

When used to set the offset coordinates using a function.

$(selector).offset(function(index,currentoffset))

{top:value,left:value}:

  • It is a mandatory parameter that specifies the top and left coordinates values. The values are accepted in pixels.

Function:

  • It is an optional parameter.
  • The function parameter is used to return an object containing the top and left coordinates.

Index:

  • The index is an argument passed within the function.
  • It is used to give an index position to an element in the set.

Currentoffset:

  • This parameter is used to provide the current coordinates.

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 offset = ("#lresult").html("left offset: <span>" + offset.left + "</span>.");
$("#tresult").html("top offset: <span>" + offset.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>