I'm using bootstrap and this is my code. how to make smooth scroll ? Please help me
<div id="navbar-normal" >
<div >
<a href="" >
<img src="assets/images/logo.svg" alt="">
</a>
<div >
<ul >
<li ><a href="#home" >Home</a></li>
<li ><a href="#about" >About</a></li>
<li ><a href="#news" >News</a></li>
<li ><a href="#contact" >Contact</a></li>
</ul>
</div>
</div>
</div>
<section id="home"><h1>Home</h1></section>
<section id="about"><h1>About</h1></section>
<section id="news"><h1>News</h1></section>
<section id="contact"><h1>Contact</h1></section>
CodePudding user response:
You don't need to use javascript to add smooth scrolling, it can be done by setting scroll-behavior: smooth;
css property.
Example:
html {
scroll-behavior: smooth;
}
However that is not supported by all browsers See caniuse.com
By using a library like scroll-js
, you can get scrolling working on browsers like safari.
CodePudding user response:
It's not obvious what you mean. If you mean that you want the page to smoothly go from one anchor link to the next, use CSS scroll-behavior
. If you want elements on the page to move smoothly as the user scrolls with their finger or mouse wheel, I would suggest Locomotive Scroll or similar. However, you're probably looking for the first option.
CSS scroll-behavior
demo:
:root {
scroll-behavior: smooth;
}
/* demo */
nav {
display: block;
height: 1rem;
position: fixed;
}
section {
height: 100vh;
padding-top: 2rem;
}
<nav>
<a href="#a">Go to A</a>
<a href="#b">Go to B</a>
<a href="#c">Go to C</a>
</nav>
<section id="a">Section A</section>
<section id="b">Section B</section>
<section id="c">Section C</section>
CodePudding user response:
in CSS use this
:root{
scroll-behavior: smooth;
}
in JavaScript use this
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener("click", function(e){
e.preventDevault()
document.querySelector(this.getAttribute('href')).scrollIntoView({
behavior: 'smooth'
})
})
})