Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding scroll event to capture vertical position #162

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions client/helpers/throttle.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
let throttleTimeout: any = null;

function throttle(callback: Function, wait = 500) {
return function () {
if (wait) {
if (throttleTimeout === null) {
throttleTimeout = setTimeout(() => {
callback();
throttleTimeout = null;
}, wait)
}
} else {
callback();
}
}
}

export default throttle;
17 changes: 13 additions & 4 deletions client/pages/Layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,27 @@ import { Link, useLocation } from 'react-router-dom';

import Filter from '../components/Filter';
import Footer from './Footer';
import throttle from '../helpers/throttle';

let oldYOffsetValue = 0;

const Layout: React.FC<{}> = ({ children }) => {
let oldYOffsetValue = 0;
const { pathname } = useLocation();

useEffect(() => {
// save last known vertical scroll position
oldYOffsetValue = window.pageYOffset;
if (pathname === '/') {
// scroll to last saved vertical scroll location
// when user navigates to home
window.scrollTo(0, oldYOffsetValue)
window.scrollTo(0, oldYOffsetValue);
const scrollEvent = throttle(() => {
// save last known vertical scroll position
oldYOffsetValue = window.scrollY || window.pageYOffset;
});
window.addEventListener('scroll', scrollEvent);
return function () {
// detach scroll listener
window.removeEventListener('scroll', scrollEvent);
};
} else {
// scroll to top when user navigates to any post
window.scrollTo(0, 0);
Expand Down