Smooth scrolling when clicking an anchor link

blog cover image
3
239 followers

We might have a couple of hyperlinks on the post. Like for table of contents of sub headers of the posts. Using Anchor links, we can make the page scroll towards the anchor but this animation happens very fast. So how do we make this smooth?

There are some plugins that do this directly but i normally dont use plugin for this simple stuff.




TLDR; We can paste the following script at the end of the body using plugins like `Header Footer Code Manager`

<script>document.querySelectorAll('a[href^="#"]').forEach(anchor => {    anchor.addEventListener('click', function (e) {        e.preventDefault();        document.querySelector(this.getAttribute('href')).scrollIntoView({            behavior: 'smooth'        });    });});</script>
  • Long Version
  1. Install the plugin `Header Footer Code Manager` in your wordpress site. This plugin allows you to insert script on header or footer of your wordpress website.
  2. Go to your menu `HFCM` and click on `Add New`
  3. Add the scmooth scrolling script.
    - Give you snippet a name for example `Smooth Scrolling Script`
    - Choose Location as `footer`
    - Copy paste the above script
  4. Hit the save button. and go back and check your posts where you have anchor link. It should be scrolling smoothly now.

Login
Create Your Free Wealthy Affiliate Account Today!
icon
4-Steps to Success Class
icon
One Profit Ready Website
icon
Market Research & Analysis Tools
icon
Millionaire Mentorship
icon
Core “Business Start Up” Training

Recent Comments

0

Login
Create Your Free Wealthy Affiliate Account Today!
icon
4-Steps to Success Class
icon
One Profit Ready Website
icon
Market Research & Analysis Tools
icon
Millionaire Mentorship
icon
Core “Business Start Up” Training