• Stars
    star
    1,970
  • Rank 23,529 (Top 0.5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 15 years ago
  • Updated 11 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Automatically make same-page links scroll smoothly

Smooth Scroll Plugin

Allows for easy implementation of smooth scrolling for same-page links.

NPM

Note: Version 2.0+ of this plugin requires jQuery version 1.7 or greater.

Setup

ES Module

npm install jquery-smooth-scroll

or

yarn add jquery-smooth-scroll

Then, use import jquery-smooth-scroll;

Note: This assumes window.jQuery is available at time of import.

CDN

<!--
  You can get a URL for jQuery from
  https://code.jquery.com
-->
<script src="SOME_URL_FOR_JQUERY"></script>
<script src="https://cdn.statically.io/gh/kswedberg/jquery-smooth-scroll/3948290d/jquery.smooth-scroll.min.js"></script>

Copy/paste

Grab the code and paste it into your own file:

Demo

You can try a bare-bones demo at kswedberg.github.io/jquery-smooth-scroll/demo/

Features

$.fn.smoothScroll

  • Works like this: $('a').smoothScroll();
  • Specify a containing element if you want: $('#container a').smoothScroll();
  • Exclude links if they are within a containing element: $('#container a').smoothScroll({excludeWithin: ['.container2']});
  • Exclude links if they match certain conditions: $('a').smoothScroll({exclude: ['.rough','#chunky']});
  • Adjust where the scrolling stops: $('.backtotop').smoothScroll({offset: -100});
  • Add a callback function that is triggered before the scroll starts: $('a').smoothScroll({beforeScroll: function() { alert('ready to go!'); }});
  • Add a callback function that is triggered after the scroll is complete: $('a').smoothScroll({afterScroll: function() { alert('we made it!'); }});
  • Add back button support by using a hashchange event listener. You can also include a history management plugin such as Ben Alman's BBQ for ancient browser support (IE < 8), but you'll need jQuery 1.8 or earlier. See demo/hashchange.html or demo/bbq.html for an example of how to implement.

Options

The following options, shown with their default values, are available for both $.fn.smoothScroll and $.smoothScroll:

{
  offset: 0,

  // one of 'top' or 'left'
  direction: 'top',

  // only use if you want to override default behavior or if using $.smoothScroll
  scrollTarget: null,

  // automatically focus the target element after scrolling to it
  // (see https://github.com/kswedberg/jquery-smooth-scroll#focus-element-after-scrolling-to-it for details)
  autoFocus: false,

  // string to use as selector for event delegation
  delegateSelector: null,

  // fn(opts) function to be called before scrolling occurs.
  // `this` is the element(s) being scrolled
  beforeScroll: function() {},

  // fn(opts) function to be called after scrolling occurs.
  // `this` is the triggering element
  afterScroll: function() {},

  // easing name. jQuery comes with "swing" and "linear." For others, you'll need an easing plugin
  // from jQuery UI or elsewhere
  easing: 'swing',

  // speed can be a number or 'auto'
  // if 'auto', the speed will be calculated based on the formula:
  // (current scroll position - target scroll position) / autoCoefficient
  speed: 400,

  // autoCoefficent: Only used when speed set to "auto".
  // The higher this number, the faster the scroll speed
  autoCoefficient: 2,

  // $.fn.smoothScroll only: whether to prevent the default click action
  preventDefault: true

}

The options object for $.fn.smoothScroll can take two additional properties: exclude and excludeWithin. The value for both of these is an array of selectors, DOM elements or jQuery objects. Default value for both is an empty array.

Setting options after initial call

If you need to change any of the options after you've already called .smoothScroll(), you can do so by passing the "options" string as the first argument and an options object as the second.

$.smoothScroll

  • Utility method works without a selector: $.smoothScroll()

  • Can be used to scroll any element (not just document.documentElement / document.body)

  • Doesn't automatically fire, so you need to bind it to some other user interaction. For example:

    $('button.scrollsomething').on('click', function() {
      $.smoothScroll({
        scrollElement: $('div.scrollme'),
        scrollTarget: '#findme'
      });
      return false;
    });
  • The $.smoothScroll method can take one or two arguments.

    • If the first argument is a number or a "relative string," the document is scrolled to that position. If it's an options object, those options determine how the document (or other element) will be scrolled.
    • If a number or "relative string" is provided as the second argument, it will override whatever may have been set for the scrollTarget option.
    • The relative string syntax, introduced in version 2.1, looks like "+=100px" or "-=50px" (see below for an example).

Additional Option

The following option, in addition to those listed for $.fn.smoothScroll above, is available for $.smoothScroll:

{
  // The jQuery set of elements you wish to scroll.
  //  if null (default), $('html, body').firstScrollable() is used.
  scrollElement: null
}

Note:

If you use $.smoothScroll, do NOT use the body element (document.body or $('body')) alone for the scrollElement option. Probably not a good idea to use document.documentElement ($('html')) by itself either.

$.fn.scrollable

  • Selects the matched element(s) that are scrollable. Acts just like a DOM traversal method such as .find() or .next().
  • Uses document.scrollingElement on compatible browsers when the selector is 'html' or 'body' or 'html, body'.
  • The resulting jQuery set may consist of zero, one, or multiple elements.

$.fn.firstScrollable

  • Selects the first matched element that is scrollable. Acts just like a DOM traversal method such as .find() or .next().
  • The resulting jQuery set may consist of zero or one element.
  • This method is used internally by the plugin to determine which element to use for "document" scrolling: $('html, body').firstScrollable().animate({scrollTop: someNumber}, someSpeed)
  • Uses document.scrollingElement on compatible browsers when the selector is 'html' or 'body' or 'html, body'.

Examples

Scroll down one "page" at a time (v2.1+)

With smoothScroll version 2.1 and later, you can use the "relative string" syntax to scroll an element or the document a certain number of pixels relative to its current position. The following code will scroll the document down one page at a time when the user clicks the ".pagedown" button:

$('button.pagedown').on('click', function() {
  $.smoothScroll('+=' + $(window).height());
});

Smooth scrolling on page load

If you want to scroll to an element when the page loads, use $.smoothScroll() in a script at the end of the body or use $(document).ready(). To prevent the browser from automatically scrolling to the element on its own, your link on page 1 will need to include a fragment identifier that does not match an element id on page 2. To ensure that users without JavaScript get to the same element, you should modify the link's hash on page 1 with JavaScript. Your script on page 2 will then modify it back to the correct one when you call $.smoothScroll().

For example, let's say you want to smooth scroll to <div id="scrolltome"></div> on page-2.html. For page-1.html, your script might do the following:

$('a[href="page-2.html#scrolltome"]').attr('href', function() {
  var hrefParts = this.href.split(/#/);
  hrefParts[1] = 'smoothScroll' + hrefParts[1];
  return hrefParts.join('#');
});

Then for page-2.html, your script would do this:

// Call $.smoothScroll if location.hash starts with "#smoothScroll"
var reSmooth = /^#smoothScroll/;
var id;
if (reSmooth.test(location.hash)) {
  // Strip the "#smoothScroll" part off (and put "#" back on the beginning)
  id = '#' + location.hash.replace(reSmooth, '');
  $.smoothScroll({scrollTarget: id});
}

Focus element after scrolling to it.

Imagine you have a link to a form somewhere on the same page. When the user clicks the link, you want the user to be able to begin interacting with that form.

  • As of smoothScroll version 2.2, the plugin will automatically focus the element if you set the autoFocus option to true.

    $('div.example').smoothScroll({
      autoFocus: true
    });
  • In the future, versions 3.x and later will have autoFocus set to true by default.

  • If you are using the low-level $.smoothScroll method, autoFocus will only work if you've also provided a value for the scrollTarget option.

  • Prior to version 2.2, you can use the afterScroll callback function. Here is an example that focuses the first input within the form after scrolling to the form:

$('a.example').smoothScroll({
  afterScroll: function(options) {
    $(options.scrollTarget).find('input')[0].focus();
  }
});

For accessibility reasons, it might make sense to focus any element you scroll to, even if it's not a natively focusable element. To do so, you could add a tabIndex attribute to the target element (this, again, is for versions prior to 2.2):

$('div.example').smoothScroll({
  afterScroll: function(options) {
    var $tgt = $(options.scrollTarget);
    $tgt[0].focus();

    if (!$tgt.is(document.activeElement)) {
      $tgt.attr('tabIndex', '-1');
      $tgt[0].focus();
    }
  }
});

Notes

  • To determine where to scroll the page, the $.fn.smoothScroll method looks for an element with an id attribute that matches the <a> element's hash. It does not look at the element's name attribute. If you want a clicked link to scroll to a "named anchor" (e.g. <a name="foo">), you'll need to use the $.smoothScroll method instead.
  • The plugin's $.fn.smoothScroll and $.smoothScroll methods use the $.fn.firstScrollable DOM traversal method (also defined by this plugin) to determine which element is scrollable. If no elements are scrollable, these methods return a jQuery object containing an empty array, just like all of jQuery's other DOM traversal methods. Any further chained methods, therefore, will be called against no elements (which, in most cases, means that nothing will happen).

Contributing

Thank you! Please consider the following when working on this repo before you submit a pull request:

  • For code changes, please work on the "source" file: src/jquery.smooth-scroll.js.
  • Style conventions are noted in the jshint grunt file options and the .jscsrc file. To be sure your additions comply, run grunt lint from the command line.
  • If possible, please use Tim Pope's git commit message style. Multiple commits in a pull request will be squashed into a single commit. I may adjust the message for clarity, style, or grammar. I manually commit all merged PRs using the --author flag to ensure that proper authorship (yours) is maintained.

More Repositories

1

jquery-tmbundle

TextMate bundle for jQuery
XML
562
star
2

jquery-expander

Expand and Collapse HTML content
JavaScript
460
star
3

jquery-cluetip

No longer maintained/supported. β€” Displays a highly customizable tooltip when the user hovers (default) or clicks (optional) the matched elements.
JavaScript
219
star
4

jquery-carousel-lite

A jQuery carousel plugin based on jCarouselLite by Ganeshji Marwaha
JavaScript
179
star
5

grunt-version

Handle versioning of a project using grunt
JavaScript
51
star
6

jquery-tinyvalidate

A (relatively) tiny form validation plugin
JavaScript
16
star
7

jquery-fancyletter

A jQuery plugin that lets you prettify your web page by styling the first letter of any element
JavaScript
12
star
8

jQuery-API-Search

JSONP API for searching the jQuery API at http://api.jquery.com/
JavaScript
10
star
9

jquery-defaulttext

sets default text overlay on top of a text input
JavaScript
8
star
10

ks.markitup.fieldtype.ee_addon

A markItUp field type for the Field Frame ExpressionEngine extension
JavaScript
8
star
11

jQuery-sameHeight

makes collection of elements all the same height
JavaScript
7
star
12

ks.clearcache.ee_addon

ExpressionEngine module to clear cache from front-end using ajax
6
star
13

jquery-summarize

A simple plugin to initially display only a certain number of children, with a "read more" link
JavaScript
6
star
14

jquery-biglinks

jQuery plugin to increase the target area of links to a containing element
JavaScript
6
star
15

jquery-socialize

jQuery Plugin for adding a group of social bookmarks to a blog post
5
star
16

hotspotter.ee_fieldtype

Image "Hotspot" fieldtype for Expression Engine's Field Frame extension
JavaScript
5
star
17

dotfiles

dot files for my MBP
Shell
5
star
18

new-tab-bookmarks

Chrome extension to show bookmarks (from folder of your choice) in new tab
Vue
5
star
19

atom-jquery

A collection of jQuery snippets derived from my TextMate bundle
CSS
4
star
20

ks.facelift.ee_addon

Uses Facelift Image Replacement script (w/o JavaScript) to convert text to images
PHP
4
star
21

ump

Version bumping without the b
JavaScript
4
star
22

jquery-columns

puts children of a containing element into the number of columns that you specify (and deals with <ol> numbering)
JavaScript
4
star
23

fusionary-tmbundle

TextMate bundle for HTML, CSS, and JavaScript to make work at Fusionary more streamlined.
4
star
24

ks.slashee.ee_addon

ExpressionEngine plugin to add or remove starting and/or ending slashes for a string
3
star
25

ks.karls-extra-head.ee_addon

ExpressionEngine extension allowing user to add any html to the end of the document head for control panel pages
2
star
26

blog.karlswedberg.com

A blog about some techie things
JavaScript
2
star
27

triib-scrape

CLI tool to extract all Triib members' workout history
JavaScript
2
star
28

ksjs

Random js functions
JavaScript
1
star
29

c2md

Output HTML clipboard contents to markdown in the terminal (MacOs only)
JavaScript
1
star
30

dotatom

My .atom files, sourced.
JavaScript
1
star
31

grwebdev-201707

Presentation for GRWebDev Meetup, 25 July 2017
JavaScript
1
star
32

tagify.ee_addon

ExpressionEngine (EE) plugin to convert [tagname param="foo"] to {tagname param="foo"} in entry field so it can be parsed by EE
PHP
1
star