How can I set and get the current web page scroll position?
I have a chat with position fixed and if you decide to close it, the page reloads and goes back to top, which is annoying for users..because they have to scroll back down to the point they were at.
If I could save the current scroll position (in a hidden input) before the page reloads, I could then set it back after it reloads.. right? But please, show me how to do it because I am new to this.
function closeChat() {
var x = document.getElementById("chatArea");
if(x.style.display == 'block'){
x.style.display = 'none';
}
window.location.assign("explore.php");
return false;
}
PS: I have to assign to the same page because I am sending a parameter through the url and when the chat is closed, the parameter is still there... so that's why
Yes, you can save the position of the scroll in your closeChat function and store it in your localstorage
function closeChat() {
var x = document.getElementById("chatArea");
if(x.style.display == 'block'){
x.style.display = 'none';
}
localStorage.setItem('scrollValue', window.scrollY) // set it here
window.location.assign("explore.php");
return false;
}
Then on page load, you just add that value to window.scrollTo(x, y)
const scrollValue = localStorage.getItem("scrollValue")
window.scrollTo(0, scrollValue ? scrollValue : 0)
Maybe you should try to get the scrollTop property of the element under the chat box. Then you store it in the local storage and access it upon closing the the chatbox.
you can save the current scroll in local storage and restore it when the page reloads
// when leaving the page
window.localStorage.setItem('scroll', x.scrollTop);
// when entering the page
x.scrollTop = localStorage.getItem('scroll');
hope it helped :)