I know a variation on this has been asked several times; I\'ve been browsing SO for a while now but either I\'m doing something wrong or I haven\'t found what I need.
<
I modified the answer from @iandisme a bit and wrapped it up as a tiny jquery plugin:
(function ($) {
'use strict';
$.fn.scrollToSimple = function ($target) {
var $container = this.first(); // Only scrolls the first matched container
var pos = $target.position(), height = $target.outerHeight();
var containerScrollTop = $container.scrollTop(), containerHeight = $container.height();
var top = pos.top + containerScrollTop; // position.top is relative to the scrollTop of the containing element
var paddingPx = containerHeight * 0.15; // padding keeps the target from being butted up against the top / bottom of the container after scroll
if (top < containerScrollTop) { // scroll up
$container.scrollTop(top - paddingPx);
}
else if (top + height > containerScrollTop + containerHeight) { // scroll down
$container.scrollTop(top + height - containerHeight + paddingPx);
}
};
})(jQuery);
I removed the calls to .animate since I was looking for instant scrolling. I also added the ability to scroll any (scrollable) container, rather than just the window. Example usage:
// scroll the window so #target is visible
$(window).scrollToSimple( $("#target") );
// scroll the scrollable element #container so that #target is visible
$("#container").scrollToSimple( $("#target") );