Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
-3
rated 0 times [  4] [ 7]  / answers: 1 / hits: 8994  / 2 Years ago, thu, april 21, 2022, 12:00:00

Is it possible using only CSS to make smooth scrolling when clicking an anchor link in react component?


...
render(
<a href="#smooth-link">Link To There</a>
....
<div id="smooth-link">
....
</div>
)

More From » css

 Answers
1

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


[#184] Thursday, April 7, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
margob

Total Points: 302
Total Questions: 89
Total Answers: 100

Location: Guadeloupe
Member since Sat, Jul 25, 2020
4 Years ago
margob questions
Mon, Jun 29, 20, 00:00, 4 Years ago
Wed, Sep 26, 18, 00:00, 6 Years ago
Sat, Sep 1, 18, 00:00, 6 Years ago
;