Custom Smooth Scroll For Anchor Links - jQuery AnchorScroll

Custom Smooth Scroll For Anchor Links - jQuery AnchorScroll
File Size: 5.18 KB
Views Total: 490
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

An alternative to the CSS scroll-behavior: smooth property that applies a smooth scroll effect with configurable speed, easing, and offset to anchor links within the document.

Ideal for landing pages or single page web apps where you'd like to navigate between sectioned contents with a configurable smooth scroll effect.

See Also:

How to use it:

1. Insert the JavaScript jquery-anchorScroll.js after loading the latest jQuery library.

<script src="/path/to/cdn/jquery.slim.min.js"></script>
<script src="/path/to/js/jquery-anchorScroll.js"></script>

2. Call the function on the target container (the whole page in this example) in which you want to enable the smooth scroll effect and done.

<nav class="nav">
  <ul>
    <li>
      <a href="#section01">Section01</a>
    </li>
    <li>
      <a href="#section02">Section02</a>
    </li>
    <li>
      <a href="#section03">Section03</a>
    </li>
    <li>
      <a href="#section04">Section04</a>
    </li>
  </ul>
</nav>
var anchorScroll = $(document).AnchorScroll({
    // options here
});

3. Determine the anchor links should be affected by the plugin. Defaults to all anchor links found within the document.

var anchorScroll = $(document).AnchorScroll({
    target: 'a[href^="#"]'
});

4. Customize the animation speed. Defaults to 500ms.

var anchorScroll = $(document).AnchorScroll({
    speed: 1000
});

5. Specify the offset in px. Defaults to 0.

var anchorScroll = $(document).AnchorScroll({
    offset: 20
});

6. Apply an easing function to the smooth scroll effect. You might need a 3rd easing library (like jQuery UI or jQuery easing plugin) for additional easing functions. Defaults to 'swing'.

var anchorScroll = $(document).AnchorScroll({
    easing: "linear"
});

7. Determine whether to center the sectioned content after scrolled. Defaults to 0.

var anchorScroll = $(document).AnchorScroll({
    center: 1
});

8. You're also allowed to pass options via data attributes as follows:

<section id="section03" 
         data-speed="300" 
         data-easing="300" 
         data-offset="-60" 
         data-center="1">
         Section 3
</section>

9. Available events which will be fired before or after scroll.

anchorScroll.on('scrollStart', function (event) {
  var target = event.target,
  settings = event.settings;
  console.log('Start');
  if( $(window).width() < 768 ) {
    settings.center = 0;
  }
});

anchorScroll.on('scrollEnd', function (event) {
  var target = event.target;
});

Changelog:

2020-10-16

  • Bugfixed

This awesome jQuery plugin is developed by Vicugn4Pac0s. For more Advanced Usages, please check the demo page or visit the official website.