Skip to content

Commit b2099e9

Browse files
committed
feat: made SmoothScroll into a reusable global effect
1 parent e26e62d commit b2099e9

File tree

2 files changed

+37
-37
lines changed

2 files changed

+37
-37
lines changed

site/src/app/page.tsx

Lines changed: 1 addition & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -9,43 +9,7 @@ import { Education } from '@/components/Education'
99
import { Skills } from '@/components/Skills';
1010
import Navbar from '@/components/Navbar';
1111
import { personalDetails, experiencesArray, projectsArray, skillsArray } from '@/app/config';
12-
13-
import { useEffect } from 'react';
14-
15-
function SmoothScroll() {
16-
useEffect(() => {
17-
const handleAnchorClick = (event: { target: any; preventDefault: () => void; }) => {
18-
const target = event.target;
19-
20-
// Check if the clicked element is an anchor link with a hash href
21-
if (
22-
target.tagName === 'A' &&
23-
target.getAttribute('href') &&
24-
target.getAttribute('href').startsWith('#')
25-
) {
26-
event.preventDefault();
27-
const element = document.querySelector(target.getAttribute('href'));
28-
29-
if (element) {
30-
const topOffset = element.getBoundingClientRect().top + window.pageYOffset - 100;
31-
32-
window.scrollTo({
33-
top: topOffset,
34-
behavior: 'smooth',
35-
});
36-
}
37-
}
38-
};
39-
40-
// Attach event listener
41-
document.addEventListener('click', handleAnchorClick);
42-
43-
// Cleanup event listener
44-
return () => document.removeEventListener('click', handleAnchorClick);
45-
}, []);
46-
47-
return null;
48-
}
12+
import SmoothScroll from '@/hooks/smoothScrollEffect';
4913

5014
export default function Portfolio() {
5115
return (

site/src/hooks/smoothScrollEffect.tsx

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { useEffect } from 'react';
2+
3+
export default function SmoothScroll() {
4+
useEffect(() => {
5+
const handleAnchorClick = (event: { target: any; preventDefault: () => void; }) => {
6+
const target = event.target;
7+
8+
// Check if the clicked element is an anchor link with a hash href
9+
if (
10+
target.tagName === 'A' &&
11+
target.getAttribute('href') &&
12+
target.getAttribute('href').startsWith('#')
13+
) {
14+
event.preventDefault();
15+
const element = document.querySelector(target.getAttribute('href'));
16+
17+
if (element) {
18+
const topOffset = element.getBoundingClientRect().top + window.pageYOffset - 100;
19+
20+
window.scrollTo({
21+
top: topOffset,
22+
behavior: 'smooth',
23+
});
24+
}
25+
}
26+
};
27+
28+
// Attach event listener
29+
document.addEventListener('click', handleAnchorClick);
30+
31+
// Cleanup event listener
32+
return () => document.removeEventListener('click', handleAnchorClick);
33+
}, []);
34+
35+
return null;
36+
}

0 commit comments

Comments
 (0)