-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
30 lines (25 loc) · 1.02 KB
/
Copy pathscript.js
File metadata and controls
30 lines (25 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
document.addEventListener('DOMContentLoaded', function() {
const sections = document.querySelectorAll('section');
const navLinks = document.querySelectorAll('nav a');
// Function to update the active navigation link
const updateActiveLink = () => {
let currentSection = '';
sections.forEach(section => {
const sectionTop = section.offsetTop;
// The 150px offset is to ensure the link becomes active a bit before the section hits the top
if (pageYOffset >= sectionTop - 150) {
currentSection = section.getAttribute('id');
}
});
navLinks.forEach(link => {
link.classList.remove('active');
if (link.getAttribute('href').substring(1) === currentSection) {
link.classList.add('active');
}
});
};
// Listen for scroll events
window.addEventListener('scroll', updateActiveLink);
// Initial call to set the active link on page load
updateActiveLink();
});