$.fn.scrollTo = function(duration){ if(duration == null){ duration = 1000; } var offset = $(this).offset().top - $(window).height()/2 + $(this).height(); $('html,body').animate({ scrollTop: offset }, duration); }
This small plugin will scroll to a selected element when calling .scrollTo() on it.
It has an optional parameter which specifies the duration of the scroll.
For example, if i would have a div with the id “#mydiv” I would let the screen scroll to it using this code:
$('#mydiv').scrollTo(); //Or, if you want the animation to be slower $('#mydiv').scrollTo(2000);
The top of the selected element will be displayed at 50% of the screen unless the scrollbar is too short, then the element will be lower on the screen.