Skip to content

Commit ab7cfc0

Browse files
committed
feat(layout): add dynamic navbar highlight on scrolling
1 parent 4481281 commit ab7cfc0

File tree

2 files changed

+25
-8
lines changed

2 files changed

+25
-8
lines changed

components/layout/navbar.tsx

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,22 +6,39 @@ import React, { useEffect, useState } from "react";
66
import { brainwave } from "@/public/assets/index";
77
import { cn } from "@/lib/utils";
88
import { navigation } from "@/constants";
9-
import { useParams } from "next/navigation";
109
import Button from "../atoms/button";
1110
import MenuSvg from "../svg/menu-svg";
1211
import { HamburgerMenu } from "../design/navbar";
1312

1413
type Props = {};
15-
type TSection = "hero" | "features" | "collaboration" | "how-to-use" | "pricing";
1614

1715
const Navbar = (props: Props) => {
18-
const params = useParams();
19-
const [hash, setHash] = useState<TSection>("hero");
16+
const [hash, setHash] = useState<string>("hero");
2017
const [openNavigation, setOpenNavigation] = useState<boolean>(false);
2118

2219
useEffect(() => {
23-
setHash(window.location.hash as TSection);
24-
}, [params]);
20+
const dynamicNavbarHighlight = () => {
21+
const sections = document.querySelectorAll("section[id]");
22+
23+
sections.forEach((current) => {
24+
if (current === null) return;
25+
26+
const sectionId = current.getAttribute("id");
27+
// @ts-ignore
28+
const sectionHeight = current.offsetHeight;
29+
const sectionTop = current.getBoundingClientRect().top - sectionHeight * 0.2;
30+
31+
if (sectionTop < 0 && sectionTop + sectionHeight > 0 && hash !== sectionId) {
32+
setHash(`#${sectionId as string}`);
33+
}
34+
});
35+
};
36+
37+
window.addEventListener("scroll", dynamicNavbarHighlight);
38+
39+
return () => window.removeEventListener("scroll", dynamicNavbarHighlight);
40+
// eslint-disable-next-line react-hooks/exhaustive-deps
41+
}, []);
2542

2643
const toggleNavigation = () => setOpenNavigation(!openNavigation);
2744
const handleClick = () => {

components/layout/section.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ type Props = {
1313

1414
const Section = ({ className, id, crosses, crossesOffset, customPaddings, children }: Props) => {
1515
return (
16-
<div
16+
<section
1717
{...(id && { id })}
1818
className={cn(
1919
"relative",
@@ -46,7 +46,7 @@ const Section = ({ className, id, crosses, crossesOffset, customPaddings, childr
4646
<SectionSvg crossesOffset={crossesOffset} />
4747
</>
4848
)}
49-
</div>
49+
</section>
5050
);
5151
};
5252

0 commit comments

Comments
 (0)