Skip to content

Instantly share code, notes, and snippets.

@Robbertdk
Created April 17, 2017 08:13

Revisions

  1. Robbertdk created this gist Apr 17, 2017.
    41 changes: 41 additions & 0 deletions Javascript Smooth Scrolling
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    /*
    * URL updates and the element focus is maintained
    *
    * originally found via in Update 3 on http://www.learningjquery.com/2007/10/improved-animated-scrolling-script-for-same-page-links
    * Author: HEATHER MIGLIORISI
    * URL: https://css-tricks.com/smooth-scrolling-accessibility/
    */

    // filter handling for a /dir/ OR /indexordefault.page
    function filterPath(string) {
    return string
    .replace(/^\//, '')
    .replace(/(index|default).[a-zA-Z]{3,4}$/, '')
    .replace(/\/$/, '');
    }

    var locationPath = filterPath(location.pathname);
    $('a[href*="#"]').each(function () {
    var thisPath = filterPath(this.pathname) || locationPath;
    var hash = this.hash;
    if ($("#" + hash.replace(/#/, '')).length) {
    if (locationPath == thisPath && (location.hostname == this.hostname || !this.hostname) && this.hash.replace(/#/, '')) {
    var $target = $(hash), target = this.hash;
    if (target) {
    $(this).click(function (event) {
    event.preventDefault();
    $('html, body').animate({scrollTop: $target.offset().top}, 1000, function () {
    location.hash = target;
    $target.focus();
    if ($target.is(":focus")){ //checking if the target was focused
    return false;
    }else{
    $target.attr('tabindex','-1'); //Adding tabindex for elements not focusable
    $target.focus(); //Setting focus
    };
    });
    });
    }
    }
    }
    });