docsifyjs / docsify

🃏 A magical documentation site generator.
https://docsify.js.org
MIT License
27.57k stars 5.67k forks source link

Sidebar: Is there a way to set active state based on route and not id? #370

Closed TimeDropsSB closed 4 years ago

TimeDropsSB commented 6 years ago

On a page, clicking on a heading link appends an id into the URL which also changes the active state of the sidebar link. For example, https://docsify.js.org/#/more-pages?id=table-of-contents sets "Table of Contents" to active.

Is there a way to keep the active state of the sidebar to "Writing more pages" instead (which is the route name) even after clicking on a heading link? Basically, is there a way for the above link to be the same as https://docsify.js.org/#/more-pages when setting the sidebar active state?

mrpotatoes commented 4 years ago

+1

I use a table of contents plugin for headings instead of the sidebar and losing the active state in the sidebar is very frustrating.

gigaga commented 4 years ago

+1, same behavior for me and same need :(

Below my workaround:

styles:

      .sidebar-nav li ul {
        display: none;
      }

code:

      // Install a specific plugin to force current sidebar item active into collapse state
      $docsify.plugins = [].concat(install, $docsify.plugins);

      function install(hook, vm) {
        function forceCollapse() {
          var elt = document.querySelector(".sidebar-nav li.active");
          if (!elt) {
            // Sub item selected, to back parent level 1
            elt = document.querySelector(".sidebar-nav li.collapse")
              .parentElement;
            while (elt.tagName !== "LI" || !elt.offsetParent) {
              if (elt.classList.contains("sidebar-nav")) return;
              elt = elt.parentElement;
            }
          }
          if (elt) {
            console.log(elt);
            elt.className = "collapse";
            elt.onclick = function(ev) {
              setTimeout(function() {
                elt.className = "collapse";
              }, 1);
            };
          }
        }

        hook.doneEach(forceCollapse);

        hook.ready(forceCollapse);
      }
stale[bot] commented 4 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.