Skip to content

Commit 94338f1

Browse files
Add active nav highlight on scroll and section change
1 parent 7b6970b commit 94338f1

2 files changed

Lines changed: 31 additions & 0 deletions

File tree

script.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,30 @@ document.querySelectorAll('.nav-links a').forEach(link => {
2424
link.addEventListener('click', () => navLinks.classList.remove('open'));
2525
});
2626

27+
// ── ACTIVE NAV HIGHLIGHT ──
28+
const sections = document.querySelectorAll('section[id]');
29+
const navAnchors = document.querySelectorAll('.nav-links a[href^="#"]');
30+
31+
function setActiveNav() {
32+
let current = '';
33+
sections.forEach(section => {
34+
const sectionTop = section.offsetTop - 100;
35+
if (window.scrollY >= sectionTop) {
36+
current = section.getAttribute('id');
37+
}
38+
});
39+
40+
navAnchors.forEach(a => {
41+
a.classList.remove('active');
42+
if (a.getAttribute('href') === `#${current}`) {
43+
a.classList.add('active');
44+
}
45+
});
46+
}
47+
48+
window.addEventListener('scroll', setActiveNav);
49+
setActiveNav();
50+
2751
// Scroll animations
2852
const observer = new IntersectionObserver((entries) => {
2953
entries.forEach(entry => {

styles.css

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,12 @@ nav.scrolled { box-shadow: 0 2px 20px rgba(0,0,0,0.08); }
5151
transition: color var(--transition);
5252
}
5353
.nav-links a:hover { color: var(--black); }
54+
.nav-links a.active {
55+
color: var(--black);
56+
font-weight: 700;
57+
border-bottom: 2px solid var(--black);
58+
padding-bottom: 2px;
59+
}
5460

5561
.nav-cta {
5662
background: var(--black);
@@ -673,6 +679,7 @@ body.dark nav {
673679
}
674680
body.dark .nav-links a { color: #888; }
675681
body.dark .nav-links a:hover { color: #fff; }
682+
body.dark .nav-links a.active { color: #fff; border-bottom-color: #fff; }
676683
body.dark .nav-cta { background: #fff; color: #000 !important; }
677684
body.dark .nav-cta:hover { background: #e8e8e8; }
678685
body.dark .hamburger span { background: #fff; }

0 commit comments

Comments
 (0)