jQuery offset() Method

Last Updated:

jQuery offset() Method

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

Get Offset

In the following example, we will get the offset value of the paragraph (first matched), relative to its parent element.

Example

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <h1>jQuery offset() Method</h1> <p>Click on the button and check your console</p> <button>Click Me</button> <script> $(document).ready(function(){ $("button").click(function(){ var x = $("p").offset(); console.log("Top offset: " +x.top); console.log("Left offset: " +x.left); }); }); </script> </body> </html>

Syntax

// To get offset $(selector).offset(); // To set offset $(selector).offset({top:value,left:value}); // To callback $(selector).offset(function(index, offset));

Parameter Values

ValueTypeExplanation
{top:value,left:value} Optional Specifies an object containing the properties top and left, which are numbers indicating the new top and left coordinates for the elements.
function(index, offset) Optional Specifies a function to return the coordinates to set.
Parameters Explanation
  • index - Returns the index position of the element in the set.
  • offset - Returns the current coordinates of the selected element.

Browser Support

Devicedesktopmobile
Browsergoogle chromesafarifirefoxinternet Exploreredgeoperagoogle chromesafarifirefoxedgeoperaandroid webviewsamsung internet
offset()YesYesYesYesYesYesYesYesYesYesYesYesYes

Set Offset

In the following example, we will set the offset value of the paragraph (first matched) to 200px (both top and left), relative to its parent element.

Example

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <h1>jQuery offset() Method</h1> <p>Try to click on the button</p> <button>Click Me</button> <script> $(document).ready(function(){ $("button").click(function(){ var x = $("p").offset({ top : 200, left: 200 }); }); }); </script> </body> </html>

Set Offset with Callback

In the following example, we will get and set the offset value of the paragraph by using a callback when the button is clicked.

Example

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <h1>jQuery offset() Method</h1> <p>Try to click on the button multiple times</p> <button>Click Me</button> <script> $(document).ready(function(){ $("button").click(function(){ var x = $("p").offset(function(index, myOffset){ newPos = new Object(); newPos.left = myOffset.left + 50; newPos.top = myOffset.top + 50; return newPos }); }); }); </script> </body> </html>

Share this Page

Meet the Author