Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Smooth Scrolling on Page Load

Tags:

jquery

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.

like image 318
Talon Avatar asked May 14 '13 03:05

Talon


1 Answers

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

like image 76
Naveed Avatar answered Oct 21 '22 19:10

Naveed