Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make selected entry in sidebar always visible, same problem like issues#395 #490

Open
xue68 opened this issue Nov 3, 2024 · 2 comments
Open

Comments

@xue68
Copy link

xue68 commented Nov 3, 2024

Feature Description

Make selected entry in sidebar always visible. same problem like #395. I want to try a new solution below. The old solution pr#471 always put the active item in the top of the sidebar list. When I merged the pr, I found it looks like strange. After I saw the solution of vitpress, I think saving the bar position is better.

Problem/Solution

This is the new sidebar.js

document.addEventListener("DOMContentLoaded", function () {
  restoreSidebarPosition();
  enableCollapsibles();
});

function enableCollapsibles() {
  const buttons = document.querySelectorAll(".hextra-sidebar-collapsible-button");
  buttons.forEach(function (button) {
    button.addEventListener("click", function (e) {
      e.preventDefault();
      const list = button.parentElement.parentElement;
      if (list) {
        list.classList.toggle("open")
      }
    });
  });
}

function saveSidebarPosition() {
  const sidebarScrollbar = document.querySelector("aside.sidebar-container > .hextra-scrollbar");
  if (sidebarScrollbar) {
    const scrollPosition = sidebarScrollbar.scrollTop;
    sessionStorage.setItem('sidebarScrollPosition', scrollPosition);
  }
}

function restoreSidebarPosition() {
  const sidebarScrollbar = document.querySelector("aside.sidebar-container > .hextra-scrollbar");
  if (sidebarScrollbar) {
    const savedPosition = sessionStorage.getItem('sidebarScrollPosition');
    
    if (savedPosition !== null) {
      sidebarScrollbar.scrollTo({
        top: parseInt(savedPosition),
        behavior: 'instant'
      });
    }

    sidebarScrollbar.addEventListener('scroll', function() {
      saveSidebarPosition();
    });
  }
}

Alternatives Considered

null

Additional Context

There may be a lot of problems with this place, please advise.

@imfing
Copy link
Owner

imfing commented Nov 3, 2024

Hi @xue68 thank you for the feedback. Would you mind opening a pull request so we can preview the above changes you proposed

@xue68
Copy link
Author

xue68 commented Nov 3, 2024

ok, the new pr #492 has been commit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants