The jQuery offset() method is used to get the current offset of the first matched element.
It provides two methods: to set or return the offset co-ordinates for the selected elements, relative to the document.
Syntax:
To RETURN the offset co-ordinates:
$(selector).offset()
To SET the offset co-ordinates:
$(selector).offset({top:value,left:value})To SET offset co-ordinates using a function:
$(selector).offset(function(index,currentoffset))
| Parameter | Description |
|---|---|
| {top:value,left:value} | It is a mandatory parameter while setting the offset. It specifies the top and left co-ordinates in pixels. |
| Function (index,currentoffset): | It is an optional parameter. It specifies a function that returns an object containing the top and left coordinates.
|
Let's take an example to demonstrate the jQuery offset() method.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var x = $("p").offset();
alert("Top: " + x.top + " Left: " + x.left);
});
});
</script>
</head>
<body>
<p>You are reading this tutorial on rookienerd.com</p>
<button>Click here to return the offset coordinates of the p element</button>
</body>
</html><!DOCTYPE html>
<html>
<head>
<title>The jQuery Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("div").click(function () {
var offset = $(this).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;}
</style>
</head>
<body>
<p>Click on any square:</p>
<span id="lresult"> </span>
<span id="tresult"> </span>
<div style="background-color:#7fffd4"></div>
<div style="background-color:#a52a2a"></div>
<div style="background-color:#7fff00"></div>
<div style="background-color:#ff1493"></div>
</body>
</html>