How to create a smooth scroll without jQuery with native JS scrollIntoView function.
Smooth scrolling allows website users to surf your one-page site without jumps and jerks when your menu is configured on the internal sections of the page through anchors links.
In this simple tutorial, I’ll show you one of the easiest ways to add smooth scrolling to your one-page site.
First of all, we need a simple HTML page.
I created one quickly in the Bootstrap page builder.
This basic page has a fixed top navigation menu and several sections.
Now I first set up the menu links to the internal sections of the page.
For this, I added a unique ID to each section element on the page and added these IDs to the corresponding menus as anchor links to these sections.
- Add unique ID’s to all sections:
<section id="features"> ...</section>
2. add an anchor link to navigation links in the navbar:
<a class="nav-link" href="#features">Features</a>
As you can see now when you click to the link browser jump to page section with an anchor.
It doesn’t look really good and breaks user interaction with the website.
See the demo on JSFiddle: https://jsfiddle.net/Bootstraptor/g6pkf5Lj/
So let’s fix it with some JavaScript magic.
In this demo we use scrollInToView() native JavaScript function without jQuery ( https://caniuse.com/#feat=scrollintoview )
Here is the code:
document.querySelectorAll('a[href^="#"]').forEach(elem => {
elem.addEventListener('click', e => {
e.preventDefault();
document.querySelector(elem.getAttribute('href')).scrollIntoView({
behavior: 'smooth',
offsetTop: 20
});
});
});
So now you can see the demo it works like a charm and without jQuery!
// You can add the following polyfill for Safari & IE support:
https://cdnjs.cloudflare.com/ajax/libs/iamdustan-smoothscroll/0.4.0/smoothscroll.min.js
See the working demo: https://jsfiddle.net/Bootstraptor/038b9smw/8/