This is a landing page project. it has 5 html sections. it also has a dynamic navigation bar at the top that links the sections. whenever a section is added in the html it is updated on the navigation bar and links you to the section that you clicked on. I want to use JavaScript to add smooth scrolling behavior whenever I click on the sections (like scrollIntoView()) here is the html of a section
let navList = document.querySelector('#navbar__list'); // stores the <ul>...</ul>
let sectionsNumber = document.querySelectorAll('h2');
const makeNavListItems = () => {
for (let i = 0; i < sectionsNumber.length; i++) {
listItem = document.createElement('li');
listItem.innerHTML = ` <a class="menu__link" href="#section${i+1}"> Section ${i+1} </a>`;
navList.appendChild(listItem);
}
};
<!-- HTML Follows BEM naming conventions
IDs are only used for sections to connect menu achors to sections -->
<header class="page__header">
<nav class="navbar__menu">
<!-- Navigation starts as empty UL that will be populated with JS -->
<ul id="navbar__list"> </ul>
</nav>
</header>
<main>
<header class="main__hero">
<h1>Landing Page </h1>
</header>
<section id="section1" data-nav="Section 1" class="your-active-class">
<div class="landing__container">
<h2>Section 1</h2>
<p>.....</p>
<p>.......</p>
</div>
I must use an event Listener to add this scrolling behavior (project requirement) so i was thinking of something like this
navList.addEventListener('click',function(event){
event.preventDefault();
if(event.target.href){document.getElementById().scrollIntoView({behavior:'smooth'})} })
so this will check if the event target is a link. the problem is I can't find a way to get the id of the element anchored in the link