PHPackages                             holisticnetworking/jquery-smooth-scroll - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. holisticnetworking/jquery-smooth-scroll

ActiveLibrary[HTTP &amp; Networking](/categories/http)

holisticnetworking/jquery-smooth-scroll
=======================================

jquery-smooth-scroll for Packagist.

063JavaScript

Since May 9Pushed 9y ago1 watchersCompare

[ Source](https://github.com/holisticnetworking/jquery-smooth-scroll)[ Packagist](https://packagist.org/packages/holisticnetworking/jquery-smooth-scroll)[ RSS](/packages/holisticnetworking-jquery-smooth-scroll/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

Smooth Scroll Plugin
====================

[](#smooth-scroll-plugin)

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

[![NPM](https://camo.githubusercontent.com/8761b01916621a533a7b6b92aafe6c3e5627544fe1b28e166075e708870b9459/68747470733a2f2f6e6f6465692e636f2f6e706d2f6a71756572792d736d6f6f74682d7363726f6c6c2e706e673f636f6d706163743d74727565)](https://npmjs.org/package/jquery-smooth-scroll)

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

Download
--------

[](#download)

Using npm:

```
npm install jquery-smooth-scroll
```

The old-fashioned way:

Go to the following URL in your browser and copy/paste the code into your own file:

Demo
----

[](#demo)

You can try a bare-bones demo at [kswedberg.github.io/jquery-smooth-scroll/demo/](https://kswedberg.github.io/jquery-smooth-scroll/demo/)

Features
--------

[](#features)

### $.fn.smoothScroll

[](#fnsmoothscroll)

- 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](https://developer.mozilla.org/en-US/docs/Web/API/HashChangeEvent). You can also include a history management plugin such as [Ben Alman's BBQ](http://benalman.com/code/projects/jquery-bbq/docs/files/jquery-ba-bbq-js.html) for ancient browser support (IE &lt; 8), but you'll need jQuery 1.8 or earlier. See [demo/hashchange.html](demo/hashchange.html) or [demo/bbq.html](demo/bbq.html) for an example of how to implement.

#### Options

[](#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 readme 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

[](#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

[](#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

[](#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
}
```

### $.fn.scrollable

[](#fnscrollable)

- Selects the matched element(s) that are scrollable. Acts just like a DOM traversal method such as `.find()` or `.next()`.
- The resulting jQuery set may consist of **zero, one, or multiple**elements.

### $.fn.firstScrollable

[](#fnfirstscrollable)

- 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)`

Examples
--------

[](#examples)

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

[](#scroll-down-one-page-at-a-time-v21)

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

[](#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 `` 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.
------------------------------------

[](#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`.
- 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
-----

[](#notes)

- To determine where to scroll the page, the `$.fn.smoothScroll` method looks for an element with an *id* attribute that matches the `` 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. ``), 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
------------

[](#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](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html). 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.

###  Health Score

22

—

LowBetter than 23% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity8

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity41

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 88% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/0e67053d752c1c21f2e23a4797ce98639837a393a7ed09fc4ba57436f611a317?d=identicon)[holisticnetworking](/maintainers/holisticnetworking)

---

Top Contributors

[![kswedberg](https://avatars.githubusercontent.com/u/3485?v=4)](https://github.com/kswedberg "kswedberg (125 commits)")[![holisticnetworking](https://avatars.githubusercontent.com/u/1148336?v=4)](https://github.com/holisticnetworking "holisticnetworking (8 commits)")[![koenpunt](https://avatars.githubusercontent.com/u/351038?v=4)](https://github.com/koenpunt "koenpunt (3 commits)")[![bistory](https://avatars.githubusercontent.com/u/108102?v=4)](https://github.com/bistory "bistory (2 commits)")[![caius](https://avatars.githubusercontent.com/u/696?v=4)](https://github.com/caius "caius (1 commits)")[![callumacrae](https://avatars.githubusercontent.com/u/472830?v=4)](https://github.com/callumacrae "callumacrae (1 commits)")[![acusti](https://avatars.githubusercontent.com/u/517889?v=4)](https://github.com/acusti "acusti (1 commits)")[![kkirsche](https://avatars.githubusercontent.com/u/947110?v=4)](https://github.com/kkirsche "kkirsche (1 commits)")

### Embed Badge

![Health badge](/badges/holisticnetworking-jquery-smooth-scroll/health.svg)

```
[![Health](https://phpackages.com/badges/holisticnetworking-jquery-smooth-scroll/health.svg)](https://phpackages.com/packages/holisticnetworking-jquery-smooth-scroll)
```

###  Alternatives

[friendsofsymfony/rest-bundle

This Bundle provides various tools to rapidly develop RESTful API's with Symfony

2.8k73.3M317](/packages/friendsofsymfony-rest-bundle)[php-http/discovery

Finds and installs PSR-7, PSR-17, PSR-18 and HTTPlug implementations

1.3k309.5M1.2k](/packages/php-http-discovery)[nyholm/psr7

A fast PHP7 implementation of PSR-7

1.3k235.4M2.4k](/packages/nyholm-psr7)[pusher/pusher-php-server

Library for interacting with the Pusher REST API

1.5k94.8M292](/packages/pusher-pusher-php-server)[spatie/crawler

Crawl all internal links found on a website

2.8k16.3M52](/packages/spatie-crawler)[react/http

Event-driven, streaming HTTP client and server implementation for ReactPHP

78126.4M414](/packages/react-http)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
