+ 3
How to scroll to sections using pure JavaScript only ?
How can i use smooth scroll' or ' scrollIntoView()' to scroll to my secrions when i click the anchor element that belongs to that secrion, using PURE JAVASCRIPT Only That's the navbar, <ul> <li><a href="#home">Home</a></li> <li><a href="#news">News</a></li> <li><a href="#contact">Contact</a></li> <li><a href="#about">About</a></li> </ul>
5 odpowiedzi
+ 5
For the navbar,
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
</ul>
that uses href="#section" to navigate to id section, the section would appeared on the top of the view without scrolling effect.
Here is an example
https://code.sololearn.com/WQL8jhmWRITv/?ref=app
For navigation with scroll effect, we can change the above html nav part, by replacing
<a href="#section">Section</a>
with
<a onclick="scrollInto('section')">Section</a>
where scrollInto() is a custom event function that call section.scrollIntoView upon on click.
function scrollInto(id) {
var elmnt = document.getElementById(id);
elmnt.scrollIntoView({
behavior: "smooth",
block: "start",
inline: "nearest"
});
}
Here is another example with nav the uses scrollIntoView JavaScript method for scroll effect navigation.
https://code.sololearn.com/WoO2OqIZ6d4y/?ref=app
+ 4
You can use window.scrollTo(x, y)
function liClicked(){
window.scrollTo(0, 400);
}
better is to use anchor tag with body{scroll-behaviour: smooth;}
+ 4
Sudarshan Rai 👑 Already answered! 😇 Adding smooth behaviour will do the work :))
https://code.sololearn.com/Wx1mQkEy0ejH/?ref=app
+ 3
Really nice implementation Calviղ :))
+ 2
However I agree with Sudarshan Rai 👑 Arb Rahim Badsa using css scroll-behavior: smooth; on root
should be the better option.
https://code.sololearn.com/Ws1HO2U0A227/?ref=app