Reputation: 23319
Is it possible to get the top position of an element using javascript/jquery ?
The element is a table, if that matters.
Upvotes: 76
Views: 155058
Reputation: 3168
Here is a JavaScript code that allows you to get the exact position of an element, in case offsetTop
returns an incorrect value:
window.onload = function() {
var element = document.getElementById('myTable');
var realTop = element.getBoundingClientRect().top + window.scrollY;
}
Upvotes: 1
Reputation: 1096
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>position demo</title>
<style>
div {
padding: 15px;
}
p {
margin-left: 10px;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
<div>
<p>Hello</p>
</div>
<p></p>
<script>
var p = $( "p" ).first();
var position = p.position();
$( "p" ).last().text( "left: " + position.left + ", top: " + position.top );
</script>
</body>
</html>
Upvotes: 0
Reputation: 165
var top = event.target.offsetTop + 'px';
Parent element top position like we are adding elemnt inside div
var rect = event.target.offsetParent;
rect.offsetTop;
Upvotes: 8
Reputation: 85214
If you want the position relative to the document then:
$("#myTable").offset().top;
but often you will want the position relative to the closest positioned parent:
$("#myTable").position().top;
Upvotes: 136
Reputation: 27421
$("#myTable").offset().top;
This will give you the computed offset (relative to document) of any object.
Upvotes: 13