• This repository has been archived on 28/Apr/2020
  • Stars
    star
    5,481
  • Rank 7,068 (Top 0.2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 11 years ago
  • Updated almost 4 years ago

Reviews

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

Repository Details

A lightweight script to animate scrolling to anchor links.

DEPRECATION NOTICE:

Smooth Scroll is, without a doubt, my most popular and widely used plugin.

But in the time since I created it, a CSS-only method for smooth scrolling has emerged, and now has fantastic browser support. It can do things this plugin can't (like scrolling to anchor links from another page), and addresses bugs and limitations in the plugin that I have never gotten around to fixing.

This plugin has run its course, and the browser now offers a better, more feature rich and resilient solution out-of-the-box.

Learn how to animate scrolling to anchor links with one line of CSS, and how to prevent anchor links from scrolling behind fixed or sticky headers.

Thanks for the years of support!


Smooth Scroll Build Status

A lightweight script to animate scrolling to anchor links. Smooth Scroll works great with Gumshoe.

View the Demo on CodePen β†’

Getting Started | Scroll Speed | Easing Options | API | What's new? | Known Issues | Browser Compatibility | License

Quick aside: you might not need this library. There's a native CSS way to handle smooth scrolling that might fit your needs.


Want to learn how to write your own vanilla JS plugins? Check out my Vanilla JS Pocket Guides or join the Vanilla JS Academy and level-up as a web developer. πŸš€


Getting Started

Compiled and production-ready code can be found in the dist directory. The src directory contains development code.

1. Include Smooth Scroll on your site.

There are two versions of Smooth Scroll: the standalone version, and one that comes preloaded with polyfills for closest(), requestAnimationFrame(), and CustomEvent(), which are only supported in newer browsers.

If you're including your own polyfills or don't want to enable this feature for older browsers, use the standalone version. Otherwise, use the version with polyfills.

Direct Download

You can download the files directly from GitHub.

<script src="path/to/smooth-scroll.polyfills.min.js"></script>

CDN

You can also use the jsDelivr CDN. I recommend linking to a specific version number or version range to prevent major updates from breaking your site. Smooth Scroll uses semantic versioning.

<!-- Always get the latest version -->
<!-- Not recommended for production sites! -->
<script src="https://cdn.jsdelivr.net/gh/cferdinandi/smooth-scroll/dist/smooth-scroll.polyfills.min.js"></script>

<!-- Get minor updates and patch fixes within a major version -->
<script src="https://cdn.jsdelivr.net/gh/cferdinandi/smooth-scroll@15/dist/smooth-scroll.polyfills.min.js"></script>

<!-- Get patch fixes within a minor version -->
<script src="https://cdn.jsdelivr.net/gh/cferdinandi/[email protected]/dist/smooth-scroll.polyfills.min.js"></script>

<!-- Get a specific version -->
<script src="https://cdn.jsdelivr.net/gh/cferdinandi/[email protected]/dist/smooth-scroll.polyfills.min.js"></script>

NPM

You can also use NPM (or your favorite package manager).

npm install smooth-scroll

2. Add the markup to your HTML.

No special markup neededβ€”just standard anchor links. Give the anchor location an ID just like you normally would.

<a data-scroll href="#bazinga">Anchor Link</a>
...
<div id="bazinga">Bazinga!</div>

Note: Smooth Scroll does not work with <a name="anchor"></a> style anchors. It requires IDs.

3. Initialize Smooth Scroll.

In the footer of your page, after the content, initialize Smooth Scroll by passing in a selector for the anchor links that should be animated. And that's it, you're done. Nice work!

<script>
	var scroll = new SmoothScroll('a[href*="#"]');
</script>

Note: The a[href*="#"] selector will apply Smooth Scroll to all anchor links. You can selectively target links using any other selector(s) you'd like. Smooth Scroll accepts multiple selectors as a comma separated list. Example: '.js-scroll, [data-scroll], #some-link'.

Scroll Speed

Smooth Scroll allows you to adjust the speed of your animations with the speed option.

This a number representing the amount of time in milliseconds that it should take to scroll 1000px. Scroll distances shorter than that will take less time, and scroll distances longer than that will take more time. The default is 300ms.

var scroll = new SmoothScroll('a[href*="#"]', {
	speed: 300
});

If you want all of your animations to take exactly the same amount of time (the value you set for speed), set the speedAsDuration option to true.

// All animations will take exactly 500ms
var scroll = new SmoothScroll('a[href*="#"]', {
	speed: 500,
	speedAsDuration: true
});

Easing Options

Smooth Scroll comes with about a dozen common easing patterns. Here's a demo of the different patterns.

Linear Moves at the same speed from start to finish.

  • Linear

Ease-In Gradually increases in speed.

  • easeInQuad
  • easeInCubic
  • easeInQuart
  • easeInQuint

Ease-In-Out Gradually increases in speed, peaks, and then gradually slows down.

  • easeInOutQuad
  • easeInOutCubic
  • easeInOutQuart
  • easeInOutQuint

Ease-Out Gradually decreases in speed.

  • easeOutQuad
  • easeOutCubic
  • easeOutQuart
  • easeOutQuint

You can also pass in your own custom easing pattern using the customEasing option.

var scroll = new SmoothScroll('a[href*="#"]', {
	// Function. Custom easing pattern
	// If this is set to anything other than null, will override the easing option above
	customEasing: function (time) {

		// return <your formulate with time as a multiplier>

		// Example: easeInOut Quad
		return time < 0.5 ? 2 * time * time : -1 + (4 - 2 * time) * time;

	}
});

API

Smooth Scroll includes smart defaults and works right out of the box. But if you want to customize things, it also has a robust API that provides multiple ways for you to adjust the default options and settings.

Options and Settings

You can pass options and callbacks into Smooth Scroll when instantiating.

var scroll = new SmoothScroll('a[href*="#"]', {

	// Selectors
	ignore: '[data-scroll-ignore]', // Selector for links to ignore (must be a valid CSS selector)
	header: null, // Selector for fixed headers (must be a valid CSS selector)
	topOnEmptyHash: true, // Scroll to the top of the page for links with href="#"

	// Speed & Duration
	speed: 500, // Integer. Amount of time in milliseconds it should take to scroll 1000px
	speedAsDuration: false, // If true, use speed as the total duration of the scroll animation
	durationMax: null, // Integer. The maximum amount of time the scroll animation should take
	durationMin: null, // Integer. The minimum amount of time the scroll animation should take
	clip: true, // If true, adjust scroll distance to prevent abrupt stops near the bottom of the page
	offset: function (anchor, toggle) {

		// Integer or Function returning an integer. How far to offset the scrolling anchor location in pixels
		// This example is a function, but you could do something as simple as `offset: 25`

		// An example returning different values based on whether the clicked link was in the header nav or not
		if (toggle.classList.closest('.my-header-nav')) {
			return 25;
		} else {
			return 50;
		}

	},

	// Easing
	easing: 'easeInOutCubic', // Easing pattern to use
	customEasing: function (time) {

		// Function. Custom easing pattern
		// If this is set to anything other than null, will override the easing option above

		// return <your formulate with time as a multiplier>

		// Example: easeInOut Quad
		return time < 0.5 ? 2 * time * time : -1 + (4 - 2 * time) * time;

	},

	// History
	updateURL: true, // Update the URL on scroll
	popstate: true, // Animate scrolling with the forward/backward browser buttons (requires updateURL to be true)

	// Custom Events
	emitEvents: true // Emit custom events

});

Custom Events

Smooth Scroll emits three custom events:

  • scrollStart is emitted when the scrolling animation starts.
  • scrollStop is emitted when the scrolling animation stops.
  • scrollCancel is emitted if the scrolling animation is canceled.

All three events are emitted on the document element and bubble up. You can listen for them with the addEventListener() method. The event.detail object includes the anchor and toggle elements for the animation.

// Log scroll events
var logScrollEvent = function (event) {

	// The event type
	console.log('type:', event.type);

	// The anchor element being scrolled to
	console.log('anchor:', event.detail.anchor);

	// The anchor link that triggered the scroll
	console.log('toggle:', event.detail.toggle);

};

// Listen for scroll events
document.addEventListener('scrollStart', logScrollEvent, false);
document.addEventListener('scrollStop', logScrollEvent, false);
document.addEventListener('scrollCancel', logScrollEvent, false);

Methods

Smooth Scroll also exposes several public methods.

animateScroll()

Animate scrolling to an anchor.

var scroll = new SmoothScroll();
scroll.animateScroll(
	anchor, // Node to scroll to. ex. document.querySelector('#bazinga')
	toggle, // Node that toggles the animation, OR an integer. ex. document.querySelector('#toggle')
	options // Classes and callbacks. Same options as those passed into the init() function.
);

Example 1

var scroll = new SmoothScroll();
var anchor = document.querySelector('#bazinga');
scroll.animateScroll(anchor);

Example 2

var scroll = new SmoothScroll();
var anchor = document.querySelector('#bazinga');
var toggle = document.querySelector('#toggle');
var options = { speed: 1000, easing: 'easeOutCubic' };
scroll.animateScroll(anchor, toggle, options);

Example 3

// You can optionally pass in a y-position to scroll to as an integer
var scroll = new SmoothScroll();
scroll.animateScroll(750);

cancelScroll()

Cancel a scroll-in-progress.

var scroll = new SmoothScroll();
scroll.cancelScroll();

Note: This does not handle focus management. The user will stop in place, and focus will remain on the anchor link that triggered the scroll.

destroy()

Destroy the current initialization. This is called automatically in the init method to remove any existing initializations.

var scroll = new SmoothScroll();
scroll.destroy();

Fixed Headers

If you're using a fixed header, Smooth Scroll will automatically offset scroll distances by the header height. Pass in a valid CSS selector for your fixed header as an option to the init.

If you have multiple fixed headers, pass in the last one in the markup.

<nav data-scroll-header>
	...
</nav>
...
<script>
	var scroll = new SmoothScroll('.some-selector',{
		header: '[data-scroll-header]'
	});
</script>

What's new?

Scroll duration now varies based on distance traveled. If you want to maintain the old scroll animation duration behavior, set the speedAsDuration option to true.

Known Issues

Reduce Motion Settings

This isn't really an "issue" so-much as a question I get a lot.

Smooth Scroll respects the Reduce Motion setting available in certain operating systems. In browsers that surface that setting, Smooth Scroll will not run and will revert to the default "jump to location" anchor link behavior.

I've decided to respect user preferences of developer desires here. This is not a configurable setting.

<body> styling

If the <body> element has been assigned a height of 100% or overflow: hidden, Smooth Scroll is unable to properly calculate page distances and will not scroll to the right location. The <body> element can have a fixed, non-percentage based height (ex. 500px), or a height of auto, and an overflow of visible.

Animating from the bottom

Animated scrolling links at the very bottom of the page (example: a "scroll to top" link) will stop animated almost immediately after they start when using certain easing patterns. This is an issue that's been around for a while and I've yet to find a good fix for it. I've found that easeOut* easing patterns work as expected, but other patterns can cause issues. See this discussion for more details.

Scrolling to an anchor link on another page

This, unfortunately, cannot be done well.

Most browsers instantly jump you to the anchor location when you load a page. You could use scrollTo(0, 0) to pull users back up to the top, and then manually use the animateScroll() method, but in my experience, it results in a visible jump on the page that's a worse experience than the default browser behavior.

Browser Compatibility

Smooth Scroll works in all modern browsers, and IE 9 and above.

Smooth Scroll is built with modern JavaScript APIs, and uses progressive enhancement. If the JavaScript file fails to load, or if your site is viewed on older and less capable browsers, anchor links will jump the way they normally would.

Note: Smooth Scroll will not runβ€”even in supported browsersβ€”if users have Reduce Motion enabled. Learn more in the "Known Issues" section.

Polyfills

Support back to IE9 requires polyfills for closest(), requestAnimationFrame(), and CustomEvent(). Without them, support starts with Edge.

Use the included polyfills version of Smooth Scroll, or include your own.

License

The code is available under the MIT License.

More Repositories

1

reef

A lightweight library for creating reactive, state-based components and UI.
JavaScript
1,058
star
2

gulp-boilerplate

A boilerplate for building web projects with Gulp.js.
JavaScript
846
star
3

kraken

A lightweight, mobile-first boilerplate for front-end web developers.
HTML
768
star
4

gumshoe

A simple vanilla JS scrollspy script.
JavaScript
731
star
5

social-sharing

Add social sharing links and buttons without the bloat.
CSS
641
star
6

tabby

Lightweight, accessible vanilla JS toggle tabs.
JavaScript
577
star
7

atomic

A tiny, Promise-based vanilla JS Ajax/HTTP plugin with great browser support.
HTML
540
star
8

build-tool-boilerplate

A simple boilerplate for using NPM tasks to build and compile JavaScript, CSS, and image files.
JavaScript
484
star
9

bouncer

A lightweight form validation script that augments native HTML5 form validation elements and attributes.
JavaScript
304
star
10

validate

A lightweight form validation script.
JavaScript
230
star
11

houdini

A simple, accessible show-and-hide/accordion script.
JavaScript
158
star
12

ebook-boilerplate

A lightweight boilerplate for self-publishing ebooks with markdown and command line.
CSS
135
star
13

htaccess

[DEPRECATED] Best practice server rules for making web pages fast and secure.
ApacheConf
93
star
14

slider

[DEPRECATED] A simple, fluid, touch-enabled carousel.
JavaScript
87
star
15

right-height

Dynamically set content areas of different lengths to the same height.
CSS
87
star
16

modals

Simple modal dialogue windows
JavaScript
85
star
17

bin

A tiny (<1kb) localStorage and sessionStorage helper library.
JavaScript
83
star
18

vanilla-javascript-cheat-sheet

Moved
80
star
19

drop

A small CSS component that turns browser-native <details> elements into dropdown menus.
JavaScript
75
star
20

vanilla-js-toolkit

A growing collection of vanilla JavaScript code snippets, helper functions, polyfills, plugins, and learning resources.
CSS
74
star
21

form-saver

A simple script that lets users save and reuse form data.
JavaScript
68
star
22

hugo-starter

A barebones starter project and theme for learning Hugo.
HTML
67
star
23

gmt-wordpress-for-web-apps

[DEPRECATED] A plugin that provides the essential components you need to power your web app with WordPress.
PHP
67
star
24

gmt-html-minify

Minify your HTML output in WordPress.
PHP
61
star
25

events

A tiny event delegation library.
JavaScript
61
star
26

buoy

[DEPRECATED] A lightweight collection of helper methods for getting stuff done with native JavaScript.
JavaScript
54
star
27

astro

Mobile-first navigation patterns.
JavaScript
53
star
28

sticky-footer

Dynamic, responsive sticky footers.
JavaScript
47
star
29

keel

A lightweight boilerplate for WordPress theme developers.
JavaScript
46
star
30

x-ray

X-Ray is a script that lets users toggle password visibility in forms.
JavaScript
46
star
31

table-of-contents

Automatically generate a table of contents from the headings on the page.
JavaScript
38
star
32

jar

A tiny (< 1kb) library that makes working with cookies easier.
JavaScript
37
star
33

saferInnerHTML

Set the HTML of an element while protecting yourself from XSS attacks.
JavaScript
29
star
34

dom-manipulation-source-code

HTML
24
star
35

gmt-image-compress-and-sharpen

[DEPRECATED] Change the default WordPress compression rate for JPGs, convert images to progressive JPGs, and sharpen images.
PHP
19
star
36

jellyfish

[DEPRECATED] A progressively enhanced image lazy loader.
JavaScript
18
star
37

learn-vanilla-js

A roadmap for learning vanilla JavaScript
HTML
18
star
38

frontend-horse-js-library

The boilerplate for the Frontend Horse livestream.
JavaScript
15
star
39

state-based-ui-source-code

JavaScript
15
star
40

petfinderAPI4everybody

A JavaScript plugin that makes it easier to use the Petfinder API.
JavaScript
14
star
41

wp-shopping-cart

[DEPRECATED - DO NOT USE] A simple PayPal shopping cart for WordPress.
PHP
14
star
42

alerts

Simple alert messages.
JavaScript
14
star
43

wp-theme-options

[DEPRECATED] Create a theme options menu that admin can use to adjust theme settings from the dashboard.
PHP
14
star
44

reef-js

The website for ReefJS.
HTML
13
star
45

progress-bars

Simple CSS progress bars.
CSS
13
star
46

writing-libraries-source-code

HTML
13
star
47

learn-vanilla-js-source-code

HTML
12
star
48

vanilla-js-guides

HTML
12
star
49

kelp

A collection of small functions for creating reactive, state-based UIs.
JavaScript
12
star
50

project-star-rating-system

A vanilla JavaScript project
HTML
11
star
51

gmt-mailchimp-wp-rest-api

Add WP Rest API hooks for JS use of the Mailchimp API.
PHP
11
star
52

apis-source-code

HTML
11
star
53

vanilla-js-list

A growing list of organizations that build sites and apps with vanilla JS
CSS
10
star
54

petfinder-api-for-wordpress

A collection of functions to help you display Petfinder listings on your WordPress site.
PHP
10
star
55

browser-storage-source-code

HTML
10
star
56

gmt-pricing-parity

Display country-specific EDD discounts to visitors.
PHP
9
star
57

snapshot

Simple image styling.
CSS
9
star
58

sw-fonts

Demo for https://gomakethings.com/improving-web-font-performance-with-service-workers/
HTML
9
star
59

gmt-remove-header-junk

[DEPRECATED] Remove the unneccessary junk WordPress adds to the header.
PHP
9
star
60

dom-injection-source-code

HTML
8
star
61

gmt-paypal-ipn-forwarder

[DEPRECATED] Forward PayPal IPN to multiple other IPN services in WordPress.
PHP
8
star
62

service-worker-pages-demo

A demo for https://gomakethings.com/saving-recently-viewed-pages-with-service-workers-and-vanilla-js/
HTML
8
star
63

gmt-slack-invites-for-edd

[DEPRECATED] Automatically invite members to your Slack team when they purchase a product.
PHP
8
star
64

vanilla-js-guidebook-labs

The labs for "The Vanilla JS Guidebook."
HTML
7
star
65

the-lean-web

CSS
7
star
66

vanilla-js-academy

PHP
7
star
67

service-workers-source-code

JavaScript
7
star
68

sw-offline-first

Demo for https://gomakethings.com/offline-first-with-service-workers-and-vanilla-js/
HTML
7
star
69

harbor-wp-theme

A free mobile-friendly WordPress theme built specifically for animal rescue organizations.
JavaScript
7
star
70

adventure

A simplish, imagination-based kitchen table RPG.
CSS
7
star
71

variable-function-scope-source-code

HTML
6
star
72

google-hosted-jquery

[DEPRECATED] Use the Google CDN version of jQuery in WordPress, with a local fallback.
PHP
6
star
73

gmt-automated-slack-invites

Automate Slack invites with WordPress.
PHP
6
star
74

games

Simple vanilla JS game demos.
HTML
5
star
75

vanilla-js-projects

HTML
5
star
76

service-worker-demo

A demo for https://gomakethings.com/writing-your-first-service-worker-with-vanilla-js/
HTML
5
star
77

gomakethings

The WordPress theme for Go Make Things
JavaScript
5
star
78

origami

[DEPRECATED] Origami has been merged into the Kraken front-end boilerplate and is no longer supported.
HTML
5
star
79

timezones

Easily calculate timezones for your next meeting.
HTML
4
star
80

arrays-objects-source-code

HTML
4
star
81

labels

Lightweight CSS labels.
CSS
4
star
82

gmt-antispambot

A shortcode for the antispambot function that's built into WordPress.
PHP
4
star
83

cferdinandi

4
star
84

web-components-source-code

HTML
4
star
85

string-array-object-source-code

HTML
4
star
86

es-modules-demo

https://gomakethings.com/an-intro-to-import-and-export-with-es-modules/
JavaScript
3
star
87

es-modules-source-code

JavaScript
3
star
88

ajax-source-code

HTML
3
star
89

strings-numbers-source-code

HTML
3
star
90

gmt-donations

[DEPRECATED] A WordPress plugin that lets you create powerful donation forms that integrate with Stripe and PayPal Express Checkout.
PHP
3
star
91

go-mobile-first

[DEPRECATED] A mobile-first boilerplate for WordPress.
PHP
3
star
92

gmt-allow-iframes

[DEPRECATED] Prevent wp_kses from removing iframe embeds
PHP
3
star
93

advanced-academy-common-issue-not-modularizing-your-code-enough

JavaScript
3
star
94

token-based-authentication-source-code

HTML
3
star
95

vanilla-js-podcast

A show about JavaScript for people who hate the complexity of modern front‑end web development.
CSS
3
star
96

javascript-essentials-source-code

Source code for the JavaScript Essentials workshop.
HTML
2
star
97

fetch

The Fetch for Petfinder plugin
JavaScript
2
star
98

es-modules-default

https://gomakethings.com/how-to-define-a-default-export-with-vanilla-js-es-modules/
JavaScript
2
star
99

accessible-components-source-code

HTML
2
star
100

careers

CSS
2
star