This snippet produces a smooth scrolling implementation which also allows us to customize the animation effect and duration.
Let’s say the navigation consists of some a
elements:
<a href="#section-1" class="trigger"></a>
<a href="#section-2" class="trigger"></a>
...
<div id="section-1">...</div>
<div id="section-2">...</div>
Clicking the link will scroll the page to a particular element that can be determined by the href
attribute.
const triggers = [].slice.call(document.querySelectorAll('.trigger'));
triggers.forEach(function(ele) {
ele.addEventListener('click', clickHandler);
});
The clickHandler
function handles the click
event of a navigation element. It determines the target section based on the href
attribute. Notice that we will scroll to the target section ourselves, hence the default action will be ignored:
const clickHandler = function(e) {
// Prevent the default action
e.preventDefault();
// Get the `href` attribute
const href = e.target.getAttribute('href');
const id = href.substr(1);
const target = document.getElementById(id);
scrollToTarget(target);
};
Customize the animation
Currently, we move to the target equally per millisecond. We move the same distance every milliseconds.
If you want, you can replace the current linear movement with other easing functions. Look at this website to imagine how each easing produces different animations.
The code below uses the easeInQuad
animation:
const easeInQuad = function(t) {
return t * t;
};
const loop = function(currentTime) {
...
const percent = Math.min(time / duration, 1);
window.scrollTo(0, startPos + diff * easeInQuad(percent));
});