Skip to content

Smooth Scroll

Chris Evans edited this page Jan 8, 2018 · 1 revision

As with all function files in your javascript application file reference to any of the geff js files required - ensuring that it is after reference to jquery:

//= require geff/smooth-scroll

After this make sure you include reference to the function in your public.js file in a document ready function. As this function effects all anchors we can just place it directly on body.

$('body').smoothScroll();

This smooth scroll function is a clean way to automatically add in a smooth croll to every anchor link in the website. If you do not want to use it, then obviously just don't even include the js file.

All credit goes to Chris Coyier found here: https://css-tricks.com/snippets/jquery/smooth-scrolling/

Once included just reference it as above and it will automatically add a smooth scroll to every anchor that contains a hashtag.

There is also the ability to edit the speed of the animation. The core functino is 1 second. Feel free to add any speed to the function like this example for a half second animation:

$('body').smoothScroll(500);

Here is the code used:

  $('a[href*="#"]')
    // Remove links that don't actually link to anything
    .not('[href="#"]')
    .not('[href="#0"]')
    .click(function(event) {
      // On-page links
      if (
        location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
        &&
        location.hostname == this.hostname
      ) {
        // Figure out element to scroll to
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
        // Does a scroll target exist?
        if (target.length) {
          // Only prevent default if animation is actually gonna happen
          event.preventDefault();
          $('html, body').animate({
            scrollTop: target.offset().top
          }, scrollSpeed, function() {
            // Callback after animation
            // Must change focus!
            var $target = $(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(); // Set focus again
            };
          });
        }
      }
    });