Smooth Scrolling When Clicking an Anchor Link

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



Leave a reply



Submit