Technologies:
Tolerim
21 hours ago
Reworded: Saves the current scroll position of the page.
As a JavaScript developer, I'm faced with an issue where I'm attempting to maintain the page's scroll offset using the following code:
document.body.addEventListener("load", function (event) {
var scrollpos = sessionStorage.getItem('scrollpos');
if (scrollpos) {
window.scrollTo(0, scrollpos);
sessionStorage.removeItem('scrollpos');
}
});
window.addEventListener("beforeunload", function (e) {
sessionStorage.setItem('scrollpos', window.scrollY);
});
Despite my attempts, the code doesn't seem to be working. Do you have any insight into what might be causing this issue?Answers(1)
Tolerim
21 hours ago
Verified Answer
The issue with the code is that the "load" event listener should be added to the "window" object instead of the "document.body" object. Here's the corrected code:
window.addEventListener("load", function (event) {
var scrollpos = sessionStorage.getItem('scrollpos');
if (scrollpos) {
window.scrollTo(0, scrollpos);
sessionStorage.removeItem('scrollpos');
}
});
window.addEventListener("beforeunload", function (e) {
sessionStorage.setItem('scrollpos', window.scrollY);
});
By adding the "load" event listener to the "window" object, it will ensure that the entire page including external resources like images and stylesheets have finished loading before retrieving the "scrollpos" value from the sessionStorage.