MrFox
Improval of Scrol-Saver
Hello, I got this code:
Any ideas how I can get it that it doesnt flicker when using this?
I use a div and added there
export default defineNuxtPlugin((nuxtApp) => {
const router = useRouter();
router.beforeEach((to, from) => {
if (!import.meta.client) return;
const sidebarRef = document.querySelector<HTMLDivElement>("[saveScroll]");
const getParentLink = (input: string) => {
let fullPath = input.replace(/^\//, "").split("/");
while (fullPath.length > 0 && /^\d+$/.test(fullPath[fullPath.length - 1])) {
fullPath.pop();
}
return "/" + fullPath.join("/") || "/";
};
if (getParentLink(from.fullPath) !== getParentLink(to.fullPath)) {
sessionStorage.removeItem("sidebarScroll");
} else {
if (sidebarRef) {
sessionStorage.setItem("sidebarScroll", sidebarRef.scrollTop.toString());
}
}
});
nuxtApp.hook("page:loading:end", () => {
if (!import.meta.client) return;
const savedPosition = sessionStorage.getItem("sidebarScroll");
const sidebarRef = document.querySelector<HTMLDivElement>("[saveScroll]");
if (savedPosition && sidebarRef) {
sidebarRef.scrollTop = parseInt(savedPosition, 10);
}
});
});
export default defineNuxtPlugin((nuxtApp) => {
const router = useRouter();
router.beforeEach((to, from) => {
if (!import.meta.client) return;
const sidebarRef = document.querySelector<HTMLDivElement>("[saveScroll]");
const getParentLink = (input: string) => {
let fullPath = input.replace(/^\//, "").split("/");
while (fullPath.length > 0 && /^\d+$/.test(fullPath[fullPath.length - 1])) {
fullPath.pop();
}
return "/" + fullPath.join("/") || "/";
};
if (getParentLink(from.fullPath) !== getParentLink(to.fullPath)) {
sessionStorage.removeItem("sidebarScroll");
} else {
if (sidebarRef) {
sessionStorage.setItem("sidebarScroll", sidebarRef.scrollTop.toString());
}
}
});
nuxtApp.hook("page:loading:end", () => {
if (!import.meta.client) return;
const savedPosition = sessionStorage.getItem("sidebarScroll");
const sidebarRef = document.querySelector<HTMLDivElement>("[saveScroll]");
if (savedPosition && sidebarRef) {
sidebarRef.scrollTop = parseInt(savedPosition, 10);
}
});
});
<div saveScroll>
... I made this because somehow Nuxt sets the scrollTop everytime to 0...34 replies