Smooth scrolling when clicking an anchor link
No need any js just use scroll-behavior: smooth at html tag Thats it
html{
scroll-behavior: smooth;
}
Smooth scrolling when clicking an anchor link on react/next.js
There's this:
/**
* Smooth scrolling inside an element
*/
#my-element {
scroll-behavior: smooth;
}
/**
* Smooth scrolling on the whole document
*/
html {
scroll-behavior: smooth;
}
Source
But I feel like JS does a better job:
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
document.querySelector(this.getAttribute('href')).scrollIntoView({
behavior: 'smooth'
});
});
});
So you could give that a try: docs
Smooth scrolling when clicking Anchor Link
you can add in css a general scroll behavior for the entire website to scroll smoothly like:
* {
scroll-behavior: smooth;
}
How to add smooth Scrolling to single anchor instead of whole page
Here is my solution using (Vanilla) JavaScript.
I just toggles the className
of the <html>
element dependent on the data-smooth-scroll
attribute being set on the link.
"use strict";
document.addEventListener('click', function(e) {
var className = 'smooth';
var classList = document.documentElement.classList;
if (e.target.dataset.smoothScroll) {
classList.add(className)
} else {
classList.remove(className)
}
})
html.smooth {
scroll-behavior: smooth;
}
section {
width: 80%;
border: 1px solid gold;
margin: 50px auto;
height: 100vh;
}
<a href="#Section1">Section 1</a><br>
<a href="#Section2">Section 2</a>
<a href="#Section3" data-smooth-scroll="1">Section 3</a>
<a class="anchor" id="Section1"> </a>
<section>
<h2>Section 2</h2>
</section>
<a class="anchor" id="Section2"> </a>
<section>
<h2>Section 2</h2>
</section>
<a class="anchor" id="Section3"> </a>
<section>
<h2>Section 3</h2>
</section>
Related Topics
What's the Difference Between '$(This)' and 'This'
How to Work Around JavaScript'S Parseint Octal Behavior
Check If an Image Is Loaded (No Errors) With Jquery
JavaScript - Sort Array Based on Another Array
How to Detect Idle Time in JavaScript
How to Access Post Form Fields in Express
Working With $Scope.$Emit and $Scope.$On
How to Check If a String "Startswith" Another String
Build Tree Array from Flat Array in JavaScript
Is There a Standard Function to Check For Null, Undefined, or Blank Variables in JavaScript
Should All Jquery Events Be Bound to $(Document)
How Does "This" Keyword Work Within a Function
How to Detect Changes in Location Hash
Can Scrapy Be Used to Scrape Dynamic Content from Websites That Are Using Ajax
"Cross Origin Requests Are Only Supported For Http." Error When Loading a Local File
$(Document).Ready Equivalent Without Jquery
JavaScript Window Resize Event
What Is the Purpose of Node.Js Module.Exports and How to Use It