I want to do the smooth scrolling, using anchors, on the same page. All my anchors are spread out on a page at different horizontal or/and vertical levels. I got this code below, which only works well with scrolling vertically, and doesn't work with scrolling horizontally. What should I do to make the the scrolling go vertically and horizontally at the same time?
$(function() {
// scroll handler
var scrollToAnchor = function( id ) {
// grab the element to scroll to based on the name
var elem = $("a[name='"+ id +"']");
// if that didn't work, look for an element with our ID
if ( typeof( elem.offset() ) === "undefined" ) {
elem = $("#"+id);
}
// if the destination element exists
if ( typeof( elem.offset() ) !== "undefined" ) {
// do the scroll
$('html, body').animate({
scrollTop: elem.offset().top
}, 1000 );
}
};
// bind to click event
$("a").click(function( event ) {
// only do this if it's an anchor link
if ( $(this).attr("href").match("#") ) {
// cancel default event propagation
event.preventDefault();
// scroll to the location
var href = $(this).attr('href').replace('#', '')
scrollToAnchor( href );
}
});
});
You should animate the scrollLeft property as well...
$('html, body').animate({
scrollTop: elem.offset().top,
scrollLeft: elem.offset().left
}, 1000 );
Or use the jquery scrollTo plugin.