-
Notifications
You must be signed in to change notification settings - Fork 0
/
headerscroller.js
44 lines (38 loc) · 1.44 KB
/
headerscroller.js
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
document.addEventListener('DOMContentLoaded', () => {
const header = document.querySelector('.header');
const navbarLinks = document.querySelectorAll('.navbar a');
// Change header style on scroll
window.addEventListener('scroll', () => {
header.classList.toggle('scrolled', window.scrollY > 0);
});
// Function to set active link
const setActiveLink = (hash) => {
const activeHash = hash || '#home'; // Default to '#home' if no hash is provided
navbarLinks.forEach(link => {
const isActive = link.getAttribute('href') === activeHash;
link.classList.toggle('active', isActive); // Add/remove 'active' class
});
};
// Set initial active state based on the URL hash
setActiveLink(window.location.hash);
// Add smooth scrolling and active link management
navbarLinks.forEach(link => {
link.addEventListener('click', (event) => {
const href = link.getAttribute('href');
if (href.startsWith('#')) {
event.preventDefault();
const targetId = href.substring(1);
const targetSection = document.getElementById(targetId);
if (targetSection) {
targetSection.scrollIntoView({ behavior: 'smooth' });
}
history.pushState(null, '', href);
setActiveLink(href); // Update active link
}
});
});
// Update active link on history navigation
window.addEventListener('popstate', () => {
setActiveLink(window.location.hash);
});
});