How to get the top position of an element?
JavascriptJqueryJavascript Problem Overview
Is it possible to get the top position of an element using javascript/jquery ?
The element is a table, if that matters.
Javascript Solutions
Solution 1 - Javascript
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;
Solution 2 - Javascript
$("#myTable").offset().top;
This will give you the computed offset (relative to document) of any object.
Solution 3 - Javascript
var top = event.target.offsetTop + 'px';
Parent element top position like we are adding elemnt inside div
var rect = event.target.offsetParent;
rect.offsetTop;
Solution 4 - Javascript
<!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>
Solution 5 - Javascript
Try:
$('#mytable').attr('offsetTop')