yesterday i found this very useful jQuery-script on github:
https://gist.github.com/853841
jQuery.fn.scrollToViewPort = function(animTimeInterval) { animTimeInterval = (typeof animTimeInterval == "undefined")?"slow":animTimeInterval; return this.each(function(){ $('html,body').animate({scrollTop: $(this).offset().top},animTimeInterval); }); }
it moves the users’ viewport to show the element that it has been called on.
I modified it somehow so that it will check now if the element is already in the viewport.
So we can avoid auto-scrolling in that case.
A offset Parameter has also been added in case we need some margin.
https://gist.github.com/1018842
jQuery.fn.scrollToViewPort = function(options) { var animTimeInterval = (typeof options.interval == "undefined")?"slow":animTimeInterval; return this.each(function(){ var offSet = (typeof options.offset == "undefined")? $(this).offset().top : options.offset; if( $(this).offset().top <= $(window).scrollTop() || ( $(this).offset().top + $(this).height() ) >= ( $(window).scrollTop() + $(window).height() ) ){ $('html,body').animate( { scrollTop: offSet }, animTimeInterval ); } }); }
usage:
$(this).scrollToViewPort( { offset : ( ( $(this).offset().top + my_custom_offset ) - $(window).height() ) } );