Skip to content

Commit

Permalink
resolve nuxt#16, remember scroll position when go back
Browse files Browse the repository at this point in the history
  • Loading branch information
ali4zimi committed Jun 7, 2023
1 parent 3786925 commit af43b70
Showing 1 changed file with 34 additions and 2 deletions.
36 changes: 34 additions & 2 deletions plugins/scroll.client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,39 @@
export default defineNuxtPlugin(() => {
const nuxtApp = useNuxtApp()

nuxtApp.$router.afterEach(async () => {
document.querySelector('[data-scroll]')?.scrollTo({ top: 9 })

// We need to check if the user is going back or not
let isBack = false;
window.onpopstate = function () {
isBack = true;
};

nuxtApp.$router.afterEach(async (to, from) => {
if (from.path === to.path) return;

const currentHistory = {
path: from.path,
scrollPosition: document.querySelector('[data-scroll]')?.scrollTop
}

const scrollHistory = JSON.parse(localStorage.getItem('scrollHistory') || '[]');

if (scrollHistory[scrollHistory.length - 1]?.path === to.path && isBack) {
// Here we check if the scroll is not biger than the scrollHeight, if it is, scroll to the bottom
if (scrollHistory[scrollHistory.length - 1]?.scrollPosition > document.querySelector('[data-scroll]')?.scrollHeight) {
document.querySelector('[data-scroll]')?.scrollTo({ top: document.querySelector('[data-scroll]')?.scrollHeight });
} else {
document.querySelector('[data-scroll]')?.scrollTo({ top: scrollHistory[scrollHistory.length - 1]?.scrollPosition })
}

scrollHistory.pop();
}
else {
scrollHistory.push(currentHistory);
document.querySelector('[data-scroll]')?.scrollTo({ top: 9 });
isBack = false;
}

localStorage.setItem('scrollHistory', JSON.stringify(scrollHistory));
})
})

0 comments on commit af43b70

Please sign in to comment.