I'm using this jQuery Script to do Smooth Scrolling (Found on CSS-Tricks.com):
/** Smooth Scrolling Functionality **/
jQuery(document).ready(function($) {
function filterPath(string) {
return string
.replace(/^\//,'')
.replace(/(index|default).[a-zA-Z]{3,4}$/,'')
.replace(/\/$/,'');
}
var locationPath = filterPath(location.pathname);
var scrollElem = scrollableElement('html', 'body');
var urlHash = '#' + window.location.href.split("#")[1];
$('a[href*=#]').each(function() {
$(this).click(function(event) {
var thisPath = filterPath(this.pathname) || locationPath;
if ( locationPath == thisPath
&& (location.hostname == this.hostname || !this.hostname)
&& this.hash.replace(/#/,'') ) {
var $target = $(this.hash), target = this.hash;
if (target) {
var targetOffset = $target.offset().top;
event.preventDefault();
$(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
location.hash = target;
});
}
}
});
});
// use the first element that is "scrollable"
function scrollableElement(els) {
for (var i = 0, argLength = arguments.length; i <argLength; i++) {
var el = arguments[i],
$scrollElement = $(el);
if ($scrollElement.scrollTop()> 0) {
return el;
} else {
$scrollElement.scrollTop(1);
var isScrollable = $scrollElement.scrollTop()> 0;
$scrollElement.scrollTop(0);
if (isScrollable) {
return el;
}
}
}
return [];
}
});
/** END SMOOTH SCROLLING FUNCTIONALITY **/
It works fantastic, except for one thing, I want it to work where if someone goes directly to the url e.g. http://domain.com/page.html#anchor
it smooth scrolls to that anchor from the top on page load, right now it immediately goes to the page anchor unless they've clicked on an anchor. I hope that makes sense.
If it is not too late for answer then here you go.... Here is a modification of PSR's code that actually works for smooth scrolling of page on load:
http://jsfiddle.net/9SDLw/1425/
$(function(){
$('html, body').animate({
scrollTop: $( $('#anchor1').attr('href') ).offset().top
}, 2000);
return false;
});
Better version:
http://jsfiddle.net/9SDLw/1432/
$(function(){
$('html, body').animate({
scrollTop: $('.myclass').offset().top
}, 2000);
return false;
});
All you need to do in this script is to replace the "myclass" with a class or ID of the control located on the page you want to scroll to.
Naveed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With