'Remember/maintain navbar scroll position between pages ( Javacript )

I have a vertical navbar on the left side of my page like this:

$active = basename($_SERVER['PHP_SELF'], ".php");

echo '<ul id="navbar">
        <li id="page1" class="'; echo ($active == 'page1') ? 'active' : ''; echo '" onclick="navbarScrollSetItem(this.id)">
          <a href="page1.php">Page 1</a>
        </li>
        <li id="page2" class="'; echo ($active == 'page2') ? 'active' : ''; echo '" onclick="navbarScrollSetItem(this.id)">
          <a href="page2.php">Page 2</a>
        </li>
        <li id="page3" class="'; echo ($active == 'page3') ? 'active' : ''; echo '" onclick="navbarScrollSetItem(this.id)">
          <a href="page3.php">Page 3</a>
        </li>

        ...

I've set the overflow to scroll and I need it to remember/maintain the scrollbar position between pages, so I've tried this:

function navbarScrollSetItem(navbarLiId) {
  let navbar = document.getElementById('navbar');
  let navbarLi = document.getElementById(navbarLiId);
  navbar.scrollTop = (navbarLi.offsetTop);
  localStorage.setItem('scrollPos', navbar.scrollTop);
  console.log('navbarLiId: ' + navbarLiId + ' scrollPos: ' + navbar.scrollTop);
}

And on load I've tried this:

function navbarScrollGetItem() {
  let navbar = document.getElementById('navbar');
  let scrollPos = localStorage.getItem('scrollPos');
  navbar.scrollTop = scrollPos;
}

But unfortunately it's not working, it's doing basically the same as this:

navbar.scrollIntoView({behavior: "auto", block: "start"});

What I really need is for the scrollbar to maintain exactly the same position on the page as if the page was never changed!

Can anyone help me out please?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source