offset()

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.

  • To return the offset: When this method is used to return the offset, it returns the offset co-ordinates of the FIRST matched element. It specifies the object's two properties: the top and left positions in pixels.
  • To set the offset: When this method is used to set the offset, it sets the offset co-ordinates of ALL matched elements.

Syntax:

To RETURN the offset co-ordinates:

snippet
$(selector).offset()

To SET the offset co-ordinates:

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

To SET offset co-ordinates using a function:

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

Parameters of jQuery offset method

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.
  • Index: It returns the index position of the element in the set.
  • Currentoffset:It returns the current coordinates of the selected element.

Example of jQuery offset() method

Let's take an example to demonstrate the jQuery offset() method.

snippet
<!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>

jQuery offset() example 2

snippet
<!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>
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents