Need help with navbar

trying to make my tree menu behave like the navbar on, say, kirby’s documentation, such that it doesn’t scroll back up/reset when i switch pages. i am vigorously stumped on this, and with little js knowledge, i don’t know how to google my way out of it yet. any help is appreciated.

I think you are after a sticky header. It is possible to do it with pure CSS and you can do it with a Javascript too with something like this plugin GitHub - rgalus/sticky-js: Library for sticky elements written in vanilla javascript

i already have that part, we have 2 separate scrolling containers for the menu and the content. what i need is for the menu to be in the same state (ie scrolled to the same place, same items collapsed) when i go to another page that has it. sorry, question may have been misleading, s/nav/side/g

If you want it in the exact same state, maybe you could save these states (scroll position and which menus are open) in a session? Sessions | Kirby

Edit: acutally, that might be a bit overkill. Maybe use localstorage or sessionstorage instead:

The idea would be that you set a short timeout if a scroll event occurs on the menu container, and then store container.scrollTop in localstorage or sessionstorage. On page load, retrieve that value and set the scroll value on the container.

const menuContainer = document.querySelector('.your_menu_class');
let t;

menuContainer.scrollTop = localStorage.scrollTop;

menuContainer.addEventListener('scroll', function() {
  let scrollTop = menuContainer.scrollTop;

  t = setTimeout(function() {
    localStorage.scrollTop = scrollTop;
  }, 300);

Alternatively, you could use AJAX/PJAX to fetch only the page content that changes between pages. That way, you won’t have to update the menu container at all. Here’s how that works:
There’s also libraries for it, like Another nice side effect is that pages load a lot faster :~)

1 Like

Or check out the JavaScript in the repo on GitHub.


thanks for the many, MANY suggestions. I’m sure one of them will work, and now I have a list of stuff to go through. : )

edit: also, for those coming across this, pretty sure js has some “before page unload” listener somewhere, will prob use that

1 Like