Git Product home page Git Product logo

smooth-scroll's Introduction

Smooth Scroll Build Status

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

Download Smooth Scroll / View the demo

Getting Started

Compiled and production-ready code can be found in the dist directory. The src directory contains development code. Unit tests are located in the test directory.

1. Include Smooth Scroll on your site.

<script src="dist/js/smooth-scroll.js"></script>

2. Add the markup to your HTML.

Turn anchor links into Smooth Scroll links by adding the [data-scroll] data attribute. Give the anchor location an ID just like you normally would.

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

3. Initialize Smooth Scroll.

In the footer of your page, after the content, initialize Smooth Scroll. And that's it, you're done. Nice work!

<script>
	smoothScroll.init();
</script>

Installing with Package Managers

You can install Smooth Scroll with your favorite package manager.

  • NPM: npm install cferdinandi/smooth-scroll
  • Bower: bower install https://github.com/cferdinandi/smooth-scroll.git
  • Component: component install cferdinandi/smooth-scroll

Working with the Source Files

If you would prefer, you can work with the development code in the src directory using the included Gulp build system. This compiles, lints, and minifies code, and runs unit tests.

Dependencies

Make sure these are installed first.

Quick Start

  1. In bash/terminal/command line, cd into your project directory.
  2. Run npm install to install required files.
  3. When it's done installing, run one of the task runners to get going:
    • gulp manually compiles files.
    • gulp watch automatically compiles files when changes are made and applies changes using LiveReload.
    • gulp test compiles files and runs unit tests.

Options and Settings

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.

Global Settings

You can pass options and callbacks into Smooth Scroll through the init() function:

smoothScroll.init({
	selector: '[data-scroll]', // Selector for links (must be a valid CSS selector)
	selectorHeader: '[data-scroll-header]', // Selector for fixed headers (must be a valid CSS selector)
	speed: 500, // Integer. How fast to complete the scroll in milliseconds
	easing: 'easeInOutCubic', // Easing pattern to use
	offset: 0, // Integer. How far to offset the scrolling anchor location in pixels
	scrollOnLoad: true, // Boolean. If true, animate to anchor on page load if URL has a hash
	callback: function ( toggle, anchor ) {} // Function to run after scrolling
});

Easing Options

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

Learn more about the different easing patterns and what they do at easings.net.

Override settings with data attributes

Smooth Scroll also lets you override global settings on a link-by-link basis using the [data-options] data attribute.

<a data-scroll
   data-options='{
					"speed": 500,
					"easing": "easeInOutCubic",
					"offset": 0
				}'
>
	Anchor Link
</a>

Note: You must use valid JSON in order for the data-options feature to work. Does not support the callback method.

Use Smooth Scroll events in your own scripts

You can also call Smooth Scroll's scroll animation events in your own scripts.

animateScroll()

Animate scrolling to an anchor.

smoothScroll.animateScroll(
	anchor, // ID of the anchor to scroll to. ex. '#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

smoothScroll.animateScroll( '#bazinga' );

Example 2

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

Example 3

smoothScroll.animateScroll( 750 );

escapeCharacters()

Escape special characters for use with animateScroll().

var toggle = smoothScroll.escapeCharacters('#1@#%^-');

destroy()

Destroy the current smoothScroll.init(). This is called automatically during the init function to remove any existing initializations.

smoothScroll.destroy();

Fixed Headers

Add a [data-scroll-header] data attribute to fixed headers. Smooth Scroll will automatically offset scroll distances by the header height. If you have multiple fixed headers, add [data-scroll-header] to the last one in the markup.

<nav data-scroll-header>
	...
</nav>

Animating links to other pages [NEW in v10]

Smooth Scroll now supports animating anchor links to other pages. Simply make sure that scrollOnLoad is set to true (the default) and point your link to the anchor on the page as normal.

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. If you need to smooth scrolling for older browsers, download the jQuery version of Smooth Scroll on GitHub.

Known Issues

  • If the <body> element has been assigned a height of 100%, 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.
  • SmoothScroll looks for a hash on the href of the link. As a result passing in an empty hash (#) will not work and will jump to the top of the page.
  • Many browsers will treat #top the same as an empty hash (#), resulting in a jump to the top of the page. To animate scrolling to the top of the page, please use a different ID.
  • To prevent the page from jumping, Smooth Scroll removes the target element's ID, scrolls, and then adds it back. As a result, elements styled using the ID as a selector will momentarily lose their styling. I recommend using classes as selectors instead.

Programatically adding [data-scroll] attributes to all anchor links

Useful if you have anchor links scattered throughout a page, or if you're using WordPress's wp_nav_menu() function. Add this code to your JavaScript:

;(function (window, document, undefined) {

	'use strict';

	// Cut the mustard
	var supports = 'querySelector' in document && 'addEventListener' in window;
	if ( !supports ) return;

	// Get all anchors
	var anchors = document.querySelectorAll( '[href*="#"]' );

	// Add smooth scroll to all anchors
	for ( var i = 0, len = anchors.length; i < len; i++ ) {
		var url = new RegExp( window.location.hostname + window.location.pathname );
		if ( !url.test( anchors[i].href ) ) continue;
		anchors[i].setAttribute( 'data-scroll', true );
	}

	// Initial smooth scroll (add your attributes as desired)
	smoothScroll.init();

})(window, document);

How to Contribute

In lieu of a formal style guide, take care to maintain the existing coding style. Please apply fixes to both the development and production code. Don't forget to update the version number, and when applicable, the documentation.

License

The code is available under the MIT License.

smooth-scroll's People

Contributors

cferdinandi avatar thibaudcolas avatar toddmotto avatar rikukissa avatar a-v-l avatar alexguzman avatar constantm avatar joelpittet avatar follesoe avatar jonashavers avatar itspg avatar alexbeletsky avatar

Watchers

James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.