Skip to content
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