Hello, I can’t make this code work on Mobile as well, it works perfectly on desktop but not on mobile, can someone help me?
This is the code:
document.addEventListener(‘DOMContentLoaded’, function () {
console.log(‘Scriptul Scroll Memory este activ!’);
const scrollKey = 'scrollPosition';
const pageKey = 'currentPage';
// Save scroll position before navigating to a product page
window.addEventListener('beforeunload', function () {
// Verifică dacă URL-ul conține numele unei categorii (de exemplu, "imbracaminte", "adidasi")
const categoryNames = ['imbracaminte', 'adidasi', 'pantofi', 'rochii', 'bluze']; // Adaugă categoriile tale aici
const currentUrl = window.location.href.toLowerCase();
for (let i = 0; i < categoryNames.length; i++) {
if (currentUrl.indexOf(categoryNames[i]) !== -1) {
console.log('Salvez poziția de scroll pentru categoria:', categoryNames[i], window.scrollY);
sessionStorage.setItem(scrollKey, window.scrollY);
sessionStorage.setItem(pageKey, currentUrl);
break;
}
}
});
// Restore scroll position when returning to the same category page
const savedPage = sessionStorage.getItem(pageKey);
const savedScroll = sessionStorage.getItem(scrollKey);
if (savedPage && savedScroll !== null && window.location.href === savedPage) {
console.log('Restaurăm poziția de scroll pentru categoria:', savedPage, savedScroll);
window.scrollTo({ top: parseInt(savedScroll, 10), behavior: 'smooth' });
}
I haven’t tried this yet, but how does it work in a scenario where you load more items (products, blog posts, etc.) via a query loop. Let’s say you see 6 items on page load and each time you click a button, it loads 6 more items and you can scroll down further.
Is it somehow possible to make the browser remember its position? Otherwise when you click back from an item you will be all the way back at the top. This can be frustrating if you scrolled down a lot and loaded a lot more items.