A common solution using jQuery is to animate the scrollTop
property to the offset y-position of the target element:
$('html,body').animate({
scrollTop: $('#anchor').offset().top
});
Demo: http://jsfiddle.net/HZejZ/1/
You might be able to listen to the hashchange
event if you want to keep your code as it is (untested):
$(window).on('hashchange', function(e) {
e.preventDefault();
var $target = $(window.location.hash);
if ( $target.length ) {
$('html,body').animate({scrollTop: $target.offset().top});
}
});
(edit: this seems to be problematic, the browser will jump even if preventDefault is called)