Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get new x/y positions of element after scroll using jQuery

Lets say I have an <a> tag as follows:

<body>
    <div class="wrapper">
        <a href="#" class="a1">Click Me</a>
    </div>
</body>

and my CSS are:

body{ padding:10px;}
.wrapper { height:1000px; width:500px;}

Currently I am using .offset() of Jquery to get the X/Y positions of <a> tag.

var offset = $(".a1").offset();
var top = offset.top;
var left = offset.left;

Now when I scroll the page and check of <a> tag's x,y co-ordinates, they remain the same, i.e. ineffective of page scrolling.
I want to get the new X,Y positions of <a> tag after scrolling the page related to the screen.
If this <a> tag gets hidden after scrolling down, I want its position in negative values.

Check this fiddle: http://jsfiddle.net/xQh5J/9/

Please help.

like image 453
Prasad Jadhav Avatar asked May 28 '13 14:05

Prasad Jadhav


1 Answers

The link element's position w.r.t. the document does not change when you scroll. To get the position of the element w.r.t. the window's top-left, you can take it's offset() and subtract the window's scrollTop form what you get:

var offset = $(".a1").offset();
var w = $(window);
alert("(x,y): ("+(offset.left-w.scrollLeft())+","+(offset.top-w.scrollTop())+")");

Demo: http://jsfiddle.net/xQh5J/10/

like image 160
techfoobar Avatar answered Oct 10 '22 22:10

techfoobar