-2

Say I have the following code:

<div style="height: 50px; width: 50px; background: black"></div>

<table id="pets" class="table-border" style="width: 800px; margin-top: 1em; border-collapse: collapse">
    <tr>
        <td>Name</td>
        <td>Breed</td>
        <td class="highlightTop">Age</td>
    </tr>
    <tr>
        <td><input type="text" name="petName" style="width: 100%"/></td>
        <td>...</td>
        <td class="highlight"><input type="numbers" name="age" style="width: 100%"/></td>
</table>

When I do $('#pets .highlightTop').position().top I get 0 back. Why? The fact that there's a 50px tall div above the table should mean that it's at least 50, should it not?

Since it isn't 50, how can I get the actual position of the element?

Thanks!

https://jsfiddle.net/c1qj09sn/

neubert
  • 15,947
  • 24
  • 120
  • 212
  • https://api.jquery.com/position/ <= position() is based upon the elements relationship to it's parent element – Taplar Jun 26 '20 at 21:27
  • Just read the [documentation](https://api.jquery.com/position/): _“Description: Get the current coordinates of the first element in the set of matched elements, **relative to the offset parent**. […] Contrast this with [.offset()](https://api.jquery.com/offset/), which retrieves the current position **relative to the document**.”_ – Sebastian Simon Jun 26 '20 at 21:27

1 Answers1

2

position returns the position of the element relative to it's parent.

So relative to #pets. Which is 0

What you are looking for is offset

the value of the offset will be in this case

50(height of the only element between your element and top of the document div) + 16px ( =1em margin-top of parent ) + 8px (body margin) = 72px

console.log($('#pets .highlightTop').offset().top);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="height: 50px; width: 50px; background: black"></div>

<table id="pets" class="table-border" style="width: 800px; margin-top: 1em; border-collapse: collapse">
    <tr>
        <td>Name</td>
        <td>Breed</td>
        <td class="highlightTop">Age</td>
    </tr>
    <tr>
        <td><input type="text" name="petName" style="width: 100%"/></td>
        <td>...</td>
        <td class="highlight"><input type="numbers" name="age" style="width: 100%"/></td>
</table>

Read more here -> jquery-difference-between-position-and-offset

Mihai T
  • 17,254
  • 2
  • 23
  • 32