I need the page to scroll just so that an element is visible.
Options I’ve tried:
-
jQuery’s
scrollTo: the problem is that the page scrolls so that the element is on top (or at least it tries to do that, much like how this works:<a name="xyz">/<a href="#xyz">). I want the minimum amount of scrolling, so that the entire element is visible (and, if the element is too tall, work like the anchor there). -
scrollIntoView: awful. I want it to scroll smoothly (like$.scrollTo($('#id1'), 'fast');). Also, it doesn’t seem to do what I want either.
What you need to do is identify the position within the page of the element, top and bottom (and left/right if you are considering horizontal scrolling). Then identify the current position of the viewport on the window, the scrollTop of the window should then be animated to whatever value will bring the other just in to view.
I just knocked up the following in this editor, so it’s untested, but will give you the general idea for a plugin.
Updated – to show version that worked for the OP, as well as a smoother version