I'm trying to change active when scrolling in nav bar but it's doesn't work with my code
Here, this is my js code
<script>
let navbar = document.getElementById("nav ul li");
let viewportHeight = window.innerHeight;
let navHeight = document.getElementById("nav ul li").offsetHeight;
let navbarLinks = document.querySelectorAll("nav ul li a");
window.addEventListener("scroll", e => {
scrollpos = window.scrollY;
navbarLinks.forEach(link => {
let section = document.querySelector(link.hash);
if (section.offsetTop <= scrollpos + 20 &&
section.offsetTop + section.offsetHeight > scrollpos + 20) {
link.classList.add("active");
} else {
link.classList.remove("active");
}
});
});
</script>
Here, this is my html code
<nav>
<div class="header">Profile</div>
<ul class="nav-links">
<li><a href="#page1" class="active">About</a></li>
<li><a href="#page2">Social</a></li>
<li><a href="#page3">MyWorks</a></li>
<li><a href="#page4">Development</a></li>
<li><a href="#page6">Encouragement</a></li>
<li><a href="#page7">Technique</a></li>
</ul>
</nav>
Ok,
I think you should use document.querySelectorAll(...) instead of document.getElementById(...), (line 2 & 4)
because you are using a CSS QUERY SELECTOR. you should use getElementById only when you are selecting an element by it's id.