Skip to content

Commit

Permalink
Changed handleNavigation to handle multiple paths
Browse files Browse the repository at this point in the history
-Now allows you to go from blog to specific section on the home page
-Adds #section to url to direct the scrolling
  • Loading branch information
hgreenstein committed Dec 14, 2023
1 parent 1911a5a commit d940e3e
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 12 deletions.
1 change: 0 additions & 1 deletion client/src/components/NavigationBar.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,6 @@ function NavigationBar({ darkMode, setDarkMode }) {
</Nav.Link>
<Nav.Link
href="/blog"
onClick={HandleNavigation}
className={
darkMode
? 'navbar-collapse-item-dark text-light'
Expand Down
37 changes: 26 additions & 11 deletions client/src/handleNavigation.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,29 @@
const handleNavigation = (e, alignToTop = true) => {
e.preventDefault();
const targetId = e.target.getAttribute('href').slice(1);
const currentPath = window.location.pathname;

if (currentPath !== '/') {
// Update the URL with the hash of the target section
window.location.href = '/#' + targetId;
} else {
// If already on the root, update only the hash
window.location.hash = targetId;
// Scroll immediately to the target section
scrollToTarget(targetId, alignToTop);
}
};

const scrollToTarget = (targetId, alignToTop) => {
const targetSection = document.getElementById(targetId);

if (targetSection) {
// Get the top position of the target section
const targetOffset =
targetSection.getBoundingClientRect().top + window.scrollY;

// Select the navbar element and get its current height
const targetOffset = targetSection.getBoundingClientRect().top + window.scrollY;
const navbar = document.querySelector('.navbar');

const navbarHeight = navbar.offsetHeight;

// Adjust the offset position by deducting the navbar's height
const offsetPosition = alignToTop
? targetOffset - navbarHeight
: targetOffset -
window.innerHeight / 2 +
targetSection.offsetHeight / 2;
: targetOffset - window.innerHeight / 2 + targetSection.offsetHeight / 2;

window.scrollTo({
top: offsetPosition,
Expand All @@ -27,4 +32,14 @@ const handleNavigation = (e, alignToTop = true) => {
}
};

// Global function to handle scrolling on page load
window.onload = () => {
const hash = window.location.hash.slice(1);
document.querySelector('.ring').style.display = 'none';
if (hash) {
scrollToTarget(hash, true);
}
};

export default handleNavigation;

0 comments on commit d940e3e

Please sign in to comment.