Search code examples
jqueryhtmlpositionfixed

Get the position of a fixed div with jquery


I have a div with position "fixed" and I want to get the value of its position relative to the whole document while the user scrolls down the page.

So, lets say I place the div on (x=0,y=0) and then the user scrolls down a bit and now, relative to the document, the div is on (X=0,y=300). I want to get that information, I want to know the exact position of that div in every moment, again, relative to the whole document, not to the window or the browser.

I've tried many things but nothing seems to get what I'm trying to.

One of them is this code, which does not work in the case of a fixed div:

var position = $("#fixed").offset(); /*it gets the position of the div
                                     "fixed" relative to the document*/
$("#fixed").html(position.top);      /*it prints the obtained
                                     value on the div "fixed"*/

Here you can find the running code, and you can see that, when you scroll down, the value of the position of the div does not change.

If I am not wrong, the code should print a new value on the div everytime it changes its vertical position relative to the document. But it turns out that it does not happen.


SOLVED:

The question was solved by codef0rmer. I was missing to track the scrolling to refresh the value of the position of the fixed div. I was an idiot. So the final code works fine the way he wrote it:

$(function () {
    var position = $("#fixed").offset();
    $("#fixed").html(position.top);

    $(window).scroll(function () {
       var position = $("#fixed").offset();
        $("#fixed").html(position.top);
    });
})

And here you can see the running code.

Thank you everyone and specially to codef0rmer.


Solution

  • you can use .offset() to get the current coordinates of the element relative to the document whereas .position() to get the current coordinates of an element relative to its offset parent.