-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added the ability to collapse navbar when scrolled with certain velocity, and table of content auto fill navbar height when collapsed
- Loading branch information
1 parent
0adf7f8
commit a8109ab
Showing
1 changed file
with
39 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
import { useScroll, useVelocity } from "framer-motion"; | ||
import { useEffect, useState } from "react"; | ||
|
||
/** | ||
* Calculates the scroll position of the given element. | ||
* | ||
* @returns an array contains [`isScrolled`, `scrollY`, `velocity`] | ||
* | ||
* `isScrolled` is true if the element is scrolled into view. | ||
* | ||
* `scrollY` A motion value that represents the scroll position of the element. | ||
* | ||
* `velocity` A motion value that represents the velocity of the element. | ||
*/ | ||
export const useScrolled = () => { | ||
const [scrolled, setScrolled] = useState(false); | ||
const { scrollY } = useScroll(); | ||
const velocity = useVelocity(scrollY); | ||
/* https://johnchourajr.medium.com/show-hide-on-scroll-with-framer-motion-b6f937c2d662 */ | ||
function update() { | ||
// If the velocity is greater than 10801, it's considered a intentional scroll | ||
// Then we set the scrolled state based on direction of scroll | ||
const sy = scrollY.get(); | ||
const syp = scrollY.getPrevious(); | ||
if (Math.abs(velocity.getVelocity()) > 10801) { | ||
if (sy < syp) { | ||
setScrolled(false); | ||
} else if (sy > 100 && sy > syp) { | ||
setScrolled(true); | ||
} | ||
} | ||
} | ||
|
||
/** update the onChange callback to call for `update()` **/ | ||
useEffect(() => { | ||
return scrollY.onChange(() => update()); | ||
}); | ||
return [scrolled, scrollY, velocity]; | ||
}; |