Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 875
m4rk Avatar asked Mar 02 '12 04:03

m4rk


People also ask

How to get position of div in jQuery?

jQuery position() MethodThe position() method returns the position (relative to its parent element) of the first matched element. This method returns an object with 2 properties; the top and left positions in pixels.

How do you find XY coordinates of a div?

If the element is in the main document you can get the DIV's coordinates with... var X=window. getComputedStyle(abc,null). getPropertyValue('left'); var Y=window.

How do you fix a position inside a div?

Set everything up as you would if you want to position: absolute inside a position: relative container, and then create a new fixed position div inside the div with position: absolute , but do not set its top and left properties. It will then be fixed wherever you want it, relative to the container.


1 Answers

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.

like image 150
codef0rmer Avatar answered Sep 22 '22 14:09

codef0rmer