I want to keep the scroll position in the sidebar, but I can't figure out what the error is. What did I do wrong in the JS script?
HTML:
<div class="sidebar">
<div class="sidebarHeader">
<h4 class="courseHeader"></h4>
</div>
<div class="sidebarMain">
<ul class="sidebarUl">
<li class="sidebarLi">
<a class = "sidebarA" href="1.2.html">1.2</a>
</li>
<li class="sidebarLi">
<a class = "sidebarA" href="2.1.html">2.1</a>
</li>
</ul>
</div>
</div>
JS:
document.querySelectorAll(".sidebarA", function() {
var sidebar = document.querySelector(".sidebar");
sidebar.scroll(0, localStorage.getItem('scrollPosition')|0);
sidebar.scroll(function () {
localStorage.setItem('scrollPosition', sidebar.scrollTop)
});});
Element#scroll does not take a function as argument so you are never saving the new position anywhere.
What you want to do instead is to listen for the scroll event:
sidebar.addEventListener('scroll', function() {
console.log(sidebar.scrollTop);
});
Another thing:
Element#querySelectorAll doesn't take a function as argument either; so
document.querySelectorAll(".sidebarA", function() { /* Stuff */ });
won't run the function you put there as a callback. If the goal is to run the code inside that function after the page has loaded, you can use the load event:
window.addEventListener('load', function() {
var sidebar // and so on...
});
here is some change in your js code, be sure that sidebarUl class must look like
.sidebarUl {
overflow-y: scroll;
height: 100vh;
width: 100px;
}
and parent element has css prop overflow:hidden
const element = document.getElementsByClassName('sidebarUl')[0]
console.log('element', element)
element.addEventListener("scroll", function(e) {
console.log('e', e.target.scrollTop);
localStorage.setItem('scrollPosition', e.target.scrollTop)
});
window.onload = function() {
const element = document.getElementsByClassName('sidebarUl')[0]
var reloading = sessionStorage.getItem("scrollPosition");
if (reloading != 0) {
element.scroll(0, localStorage.getItem('scrollPosition')|0);
}
}