I've got a container with a whole bunch of text in it and i want to auto-scroll to various elements in that container. I can animate the container using jQuery to scroll a certain distance nicely, however I am having a lot of trouble determining what that distance is.
Most of the hints I see recommend using the .offset().top property to get that distance, but that isn't working in this case. Have a look at this jsfiddle for an example.
NOTE: the fiddle targets paragraph tags that are direct children of the container, but I don't want to rely on that. I want to be able to get the proper scroll distance for any elements, no matter how deeply nested they may be.
Try using this:
.scrollTop()
gives the current scroll position of the DIV, add the position of the P element to it and scrolling will be fine..offset()
gets you the position of the element relative to the entire page.What you need here is
.position()
that will get you the position of the element relative to the top of its containing element.EDIT: Here it works with the updated JSFiddle
EDIT 2: I just noticed its not going to work without adding the scroll position. You'll need to add
.scrollTop()
from the containing div. Here is an updated JSFiddle. (It works this time)