Element Coordinates
In this page:
offset()
.offset() returns an element's top and left coordinates measured from the very top-left corner of the whole document, ignoring any parent. It's the right choice when you need an element's absolute position on the page, regardless of how it's nested.
Example: offset()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box" style="margin-top:100px">Box</div>
<script>
console.log($("#box").offset());
</script>
</body>
</html>
position()
position() returns an element's position relative to its offset parent -- typically the nearest ancestor with non-static CSS positioning -- rather than the whole document. This matches how the browser itself calculates position for absolutely positioned elements.
Example: position()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div style="position:relative"><div id="box" style="position:absolute;top:10px">Box</div></div>
<script>
console.log($("#box").position());
</script>
</body>
</html>
Setting Offset
offset() can also set an element's document position by passing an object with top and left values. This only works as expected on elements whose CSS position isn't static, since offset ultimately manipulates the element's positioned coordinates.
Example: Setting Offset
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box" style="position:absolute">Box</div>
<script>
$("#box").offset({top: 100, left: 50});
</script>
</body>
</html>
Comparing offset() and position()
Use offset() when you need coordinates relative to the whole document, such as aligning a tooltip with an element anywhere on the page. Use position() when you need coordinates relative to a specific positioned container the element lives inside.
Example: Comparing offset() and position()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box">Box</div>
<script>
console.log("Document-relative:", $("#box").offset());
console.log("Parent-relative:", $("#box").position());
</script>
</body>
</html>
Using Coordinates
Coordinates from offset() or position() can help place simple floating elements, like a custom dropdown or tooltip, exactly next to the element that triggered them. They're also useful for calculating the distance between two elements on the page.
Example: Using Coordinates
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="trigger">Show Tooltip</button>
<script>
$("#trigger").on("click", function() {
const pos = $(this).offset();
console.log("Place tooltip at:", pos.left, pos.top);
});
</script>
</body>
</html>
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: