MrFox
MrFox
NNuxt
Created by MrFox on 3/26/2025 in #❓・help
Improval of Scrol-Saver
Hello, I got this code:
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);
}
});
});
Any ideas how I can get it that it doesnt flicker when using this? I use a div and added there <div saveScroll>... I made this because somehow Nuxt sets the scrollTop everytime to 0...
34 replies