Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery offset values changes by scrolling the page

Tags:

jquery

var offset = $(selector).offset(); 

The values of offset variable changes if we scroll the page up and down, i want the exact and fixed offset values while keeping the position of the "selector" default(static).How can i do this?

like image 329
Gaurav Avatar asked Apr 24 '12 12:04

Gaurav


People also ask

What is offset in scroll?

Definition and Usage. The pageXOffset property returns the pixels a document has scrolled from the upper left corner of the window. The pageXOffset property is equal to the scrollX property.

How does jQuery calculate offset value?

jQuery offset() MethodThe offset() method set or returns the offset coordinates for the selected elements, relative to the document. When used to return the offset: This method returns the offset coordinates of the FIRST matched element. It returns an object with 2 properties; the top and left positions in pixels.

Is jQuery scrollable?

jQuery. scrollable manages animated scrolling in windows, scrollable elements and iframes. It frees you from handling gotchas and edge cases and offers convenient, flexible options for animation. If you are a happy user of this project already, you can support its development by donating to it.

What does scrollTop return?

The scrollTop() method sets or returns the vertical scrollbar position for the selected elements.


2 Answers

You could always calculate the offset, factoring in the scroll position:

var offset_t = $(selector).offset().top - $(window).scrollTop(); var offset_l = $(selector).offset().left - $(window).scrollLeft(); 
like image 170
trickyzter Avatar answered Sep 21 '22 21:09

trickyzter


One other potential cause is if your <body> happens to have CSS that sets overflow-x: hidden; - that completely breaks jQuery's offset() method.

In that case, $(window).scrollTop() is always 0, so the accepted answer does not work.

like image 27
Nathan Friedly Avatar answered Sep 18 '22 21:09

Nathan Friedly