How to get the top position of an element?

JavascriptJquery

Javascript 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')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioneKek0View Question on Stackoverflow
Solution 1 - JavascriptPrestaulView Answer on Stackoverflow
Solution 2 - JavascriptxandyView Answer on Stackoverflow
Solution 3 - JavascriptItisha-systematixView Answer on Stackoverflow
Solution 4 - JavascriptPriteshView Answer on Stackoverflow
Solution 5 - JavascriptairportyhView Answer on Stackoverflow