Skip to content

Commit acb9505

Browse files
committed
Set class active scrolled Id in menu
1 parent 12c83eb commit acb9505

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed

app/components/header/_children/menu.js

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,33 @@
11
'use client';
22

3+
import useScroll from '@/hooks/useScroll';
34
import useTranslate from '@/hooks/useTranslate';
45
import { useMenuStore } from '@/store/menu';
5-
import { useCallback } from 'react';
6+
import { useCallback, useEffect } from 'react';
67

78
const Menu = ({ className }) => {
89
const { active, setActive } = useMenuStore();
910
const { translate } = useTranslate();
11+
const { isScrolledIntoView } = useScroll();
12+
13+
const scrolledActive = useCallback(() => {
14+
const isScrolledAbout = isScrolledIntoView('about');
15+
const isScrolledSkills = isScrolledIntoView('skills');
16+
if (isScrolledAbout) {
17+
setActive('about');
18+
} else if (!isScrolledAbout && !isScrolledSkills) {
19+
setActive('experience');
20+
} else if (isScrolledSkills) {
21+
setActive('skills');
22+
}
23+
}, [setActive, isScrolledIntoView]);
24+
25+
useEffect(() => {
26+
window.addEventListener('scroll', scrolledActive);
27+
return () => {
28+
window.removeEventListener('scroll', scrolledActive);
29+
};
30+
}, [scrolledActive]);
1031

1132
const activeClass = useCallback(
1233
(value) => {

hooks/useScroll.js

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,14 +14,27 @@ const useScroll = () => {
1414
}
1515
};
1616

17+
const isScrolledIntoView = (id) => {
18+
const el = document.getElementById(id);
19+
const rect = el.getBoundingClientRect();
20+
const clientHeight = document.documentElement.clientHeight;
21+
const clientWidth = document.documentElement.clientWidth;
22+
return (
23+
rect.top >= 0 &&
24+
rect.left >= 0 &&
25+
rect.bottom <= (window.innerHeight || clientHeight) &&
26+
rect.right <= (window.innerWidth || clientWidth)
27+
);
28+
};
29+
1730
useEffect(() => {
1831
window.addEventListener('scroll', hasScrolled);
1932
return () => {
2033
window.removeEventListener('scroll', hasScrolled);
2134
};
2235
}, []);
2336

24-
return { isScroll };
37+
return { isScroll, isScrolledIntoView };
2538
};
2639

2740
export default useScroll;

0 commit comments

Comments
 (0)