Smooth scrolling when clicking an anchor link
3
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
- 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.
- Go to your menu `HFCM` and click on `Add New`
- Add the scmooth scrolling script.
- Give you snippet a name for example `Smooth Scrolling Script`
- Choose Location as `footer`
- Copy paste the above script - Hit the save button. and go back and check your posts where you have anchor link. It should be scrolling smoothly now.
Create Your Free Wealthy Affiliate Account Today!
4-Steps to Success Class
One Profit Ready Website
Market Research & Analysis Tools
Millionaire Mentorship
Core “Business Start Up” Training
Recent Comments
0
Create Your Free Wealthy Affiliate Account Today!
4-Steps to Success Class
One Profit Ready Website
Market Research & Analysis Tools
Millionaire Mentorship
Core “Business Start Up” Training