Reputation: 1
My navigation bar is self populated with javascript.
function liCreation() {
for(noOfSection of noOfsections) {
sectionAddress = noOfSection.getAttribute('data-nav');
section =noOfSection.getAttribute('id');
liTag = document.createElement('li');
liTag.innerHTML = `<a class='menu__link'>${sectionAddress}</a>`;
}
}
So it comes out with a navigation bar menu that has 4 sections (because I got 4 sections in my page)
I want to scroll to a section without adding href="${section}"
to the anchor element.
Upvotes: 0
Views: 115
Reputation: 177691
Why? It gives several benefits. Href shows the arrow pointer and no code is needed to scroll
If you must, then
document.querySelector("ul.nav").addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.tagname === "A" && tgt.classList.contains("menu__link")) {
document.getElementById(tgt.textContent.trim()).scrollIntoView();
}
})
assuming the id is in the text of the anchor and the ul containing the LIs have a class of .nav
Upvotes: 1