pure js smooth scrolling
by arsenlol
HTML
<header>
<nav>
<a href="#home">Home</a>
<a href="#about">About</a>
<a href="#contacts">Contacts</a>
</nav>
</header>
<main>
<section id="home">Home</section>
<section id="about">About</section>
<section id="contacts">Contacts</section>
</main>
CSS
html {
/* THIS IS SMOOTH */
scroll-behavior: smooth;
}
body {
margin: 0;
font-size: 30px;
box-sizing: border-box;
text-align: center;
}
header {
background: rgb(155 183 118);
height: 90px;
position: fixed;
width: 100%;
}
main {
padding-top: 90px;
}
nav {
line-height: 90px;
}
section {
height: 500px;
background: #5490fc;
margin-bottom: 10px;
}
a {
color: #000;
}
JavaScript
document.querySelectorAll("header nav a").forEach(function (a) {
a.addEventListener("click", function (event) {
event.preventDefault();
const hash = event.target.getAttribute("href");
const scrollTarget = document.querySelector(hash);
// Some additional logic
const headerHeight = 90;
window.scrollTo(0, scrollTarget.offsetTop - headerHeight);
});
});