I have coded a nav bar using JS, I need to add a smooth scroll active when a user clicks on one of the section written in pure JS (and not CSS's smooth scrolling) I was thinking something with scrollIntoView or scrollTo but each time I code it it either makes the navbar disappear or not work at all. Here's my navbar code. Any help is appreciaited.
function navBar() {
const section = document.getElementsByTagName('section');
for (let i = 0; i < section.length; i++) {
let navBarUL = document.getElementById("navBarULID");
let link = `<a href='#' onclick="console.log(${i})" id='link_no${i+1}'> Section ${i+1} </a>`;
let newLI = document.createElement("li")
newLI.innerHTML = link
navBarUL.appendChild(newLI)
let j = i
}
for (let i = 0; i < section.length; i++) {
document.getElementById( 'link_no' + (i + 1)).addEventListener('click', function(e) {
e.preventDefault();
let allActiveLinks = document.getElementsByClassName('active-link');
for (let i = 0; i < allActiveLinks.length; i++) {
const element = allActiveLinks[i];
element.classList.remove('active-link');
}
Here's an HTML sample
<ul id="navBarULID"></ul>
</nav>
</header>
<main>
<header class="main__hero">
<h1 id="p1">Landing Page </h1>
</header>
<section id="section1" class="your-active-class">
<div class="landing__container">
<h2 id="section1ID">Section 1</h2>
<p>test.</p>
</div>
</section>
<section id="section2" >
<div class="landing__container">
<h2 id="section2ID">Section 2</h2>
<p>test.</p>
</div>
</section>
<section id="section3" >
<div class="landing__container">
<h2 id="section3ID">Section 3</h2>
<p>test.</p>
</div>
</section>
use this CSS code
html { scroll-behavior: smooth; }