doub1ejack
doub1ejack

Reputation: 11171

how to make container scroll to element

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.

Upvotes: 2

Views: 5654

Answers (2)

Yoeri
Yoeri

Reputation: 1906

Try using this:

var pOffset = $("#lipsum").scrollTop();
pOffset = pOffset + $("#lipsum p.active").position().top; 

.scrollTop() gives the current scroll position of the DIV, add the position of the P element to it and scrolling will be fine.

Upvotes: 6

DangerMonkey
DangerMonkey

Reputation: 385

.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)

Upvotes: 4

Related Questions