-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript_navbar.js
More file actions
57 lines (48 loc) · 1.5 KB
/
script_navbar.js
File metadata and controls
57 lines (48 loc) · 1.5 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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
document.addEventListener('DOMContentLoaded', function () {
const navBar = document.getElementById('navbar');
const sections = document.querySelectorAll('.section');
const navLinks = document.querySelectorAll('nav a');
const sectionPositions = [];
sections.forEach(section => {
sectionPositions.push(section.offsetTop);
});
window.addEventListener('scroll', () => {
const scrollY = window.pageYOffset;
let currentIndex = sectionPositions.length - 1;
sectionPositions.forEach((position, index) => {
if (scrollY >= position) {
currentIndex = index;
}
});
navLinks.forEach(link => {
link.classList.remove('active');
});
navLinks[currentIndex].classList.add('active');
sections.forEach((section, index) => {
if (index === currentIndex) {
section.classList.add('active');
} else {
section.classList.remove('active');
}
});
});
window.addEventListener('scroll', () => {
if (window.scrollY > 50) {
navBar.classList.add('fixed-section');
} else {
navBar.classList.remove('fixed-section');
}
});
navLinks.forEach(link => {
link.addEventListener('click', function (event) {
event.preventDefault();
const targetId = this.getAttribute('href').substring(1);
const targetSection = document.getElementById(targetId);
const targetOffset = targetSection.offsetTop;
window.scrollTo({
top: targetOffset,
behavior: 'smooth'
});
});
});
});