Search code examples
javascripthtmlcssjekyll

Nested Menu not responding correctly


QUESTIONS:

Is there a way of changing the design so that:

  1. The menu doesn't fully collapse when a new page loads, but instead just the active branch of the menu remains open and others are collapsed.

  2. Change the scroll position in the menu on a page load, so that the currently selected menu item appears at the top of the menu scrollable area

My page, as it stands >> https://startech-enterprises.github.io/docs/data-integration-and-etl/branches-and-loops-local.html

Both desired behaviours are exhibited correctly here:

  1. https://learn.microsoft.com/en-gb/dotnet/csharp/tutorials/intro-to-csharp/branches-and-loops-local (this site reloads the whole page, on a menu click, like what my page currently does)
  2. https://firebase.google.com/docs/admin/setup#c_4 (this site only loads the content section of the page, on a menu click)

Thanks

ST

NOTE The code in the link above has now been updated for part 1 of the question, based on the answers given below

STRUCTURE OF LAYOUT PAGE:

High Level Layout:

<html>
<head></head>
<body>
<header></header>
<div class = "middle section">
<div class = "left side-bar">
{% include navigation.html %}
</div>
<div class = "contents">
{{content}}
</div>
</div>
<footer></footer>
</body>
</html>

CONTENT PAGES using LIQUID/JEKYLL:

Every content has the front matter like so:

layout: default

Generated NAV BAR using LIQUID/JEKYLL:

<ul class="treegroup">
  {% for item in include.nav %}
    {% if item.link %}
      <li {% if item.link == page.url | prepend:site.baseurl %} class="is-active"{% endif %} class="none"><a href="{{ item.link }}">{{ item.name }}</a></li>
    {% else %}
      <li {% if item.link == page.url | prepend:site.baseurl %} class="is-active"{% endif %} class="treeitem"><span class="tree-expander"><span class="tree-indicator"><img src="/../docs/assets/images/chevron.png" class="chevron"></span>{{ item.name }}</span></li>
    {% endif %}
        {% if item.tree %}
          {% include navigation.html nav=item.tree %}
        {% else %}  
        {% endif %}
      </li>
  {% endfor %}
</ul>

YML NAV file used by LIQUID/JEKYLL (as used in Liquid/Jekll code above)

tree:
- name: Level 1
  link: /docs/level1.html
- name: Level 2
  link: /docs/level2.html
- name: Level 3
  tree:
  - name: Home  
    link: /docs/index.html
  - name: About
    link: /docs/about.html
  - name: Level 3.2
    tree:
      - name: Staff
        link: /docs/staff.html
      - name: People
- name: Level 4
  link: /docs/level4.html
- name: Level 5
  tree:
  - name: Blog
    link: /docs/blog.html
  - name: Level 5.2
    tree:
      - name: Branches & Loops
        link: /docs/data-integration-and-etl/branches-and-loops-local.html
      - name: People
        link: /docs/people.html

JAVASCRIPT on SIDEBAR: (to expand / collapse menu elements when clicking with mouse) /** * Expand or collapse menu */

"use strict";
(function tree() {
    let menu = document.querySelector('.toc');
    let elements = menu.getElementsByClassName("treeitem");
    let sibling = null;
    let expanded = false;

    eventListeners();

    function eventListeners(){
        // Listen for click
        Array.from(elements).forEach(function(element) {
            element.addEventListener('click', function(ev) {
                let e = null;
                ev.target.classList.contains("treeitem") ? e = ev.target : e = parent_by_selector(ev.target, "treeitem");
                sibling = nextByClass(e, "treegroup")

                sibling.classList.contains('is-expanded') ? expanded = true : expanded = false;  
                    if(expanded){
                        e.classList.remove("is-expanded");
                        sibling.classList.remove("is-expanded");
                    } else {
                        e.classList.add("is-expanded");
                        sibling.classList.add("is-expanded");
                    } 
            }, false);
          });
    }

})();

// WAIT TILL DOCUMENT HAS LOADED BEFORE INITIATING FUNCTIONS
document.addEventListener('DOMContentLoaded', tree);

OTHER JS FUNCTIONS USED IN SCRIPT ABOVE (Helper functions)

// Find parent with given selector
function parent_by_selector(elem, selector, stop_selector = 'body') {
    let parent = elem;
    while (true) {
      if (parent.classList.contains(stop_selector)) break;
      if (parent.classList.contains(selector)) break;
      parent = parent.parentElement; // get upper parent and check again
    }
    if (parent.classList.contains(stop_selector)) parent = null; // when parent is a tag 'body' -> parent not found
    return parent;
  };

// Find child with given selector
function child_by_selector(elem, selector) {
    let children = elem.childNodes;
    for (let i = 0; i < children.length; i++) {
        if (children[i].className &&
            children[i].className.split(' ').indexOf(selector) >= 0) {
            return children[i];
         }
     }
     for (let i = 0; i < children.length; i++) {
         let child = child_by_selector(children[i], selector);
         if (child !== null) {
             return child;
         }
     }
     return null;
}

// Find next sibling of particular class
function nextByClass(elem, cls) {
    while (elem = elem.nextElementSibling) {
        if (hasClass(elem, cls)) {
            return elem;
        }
    }
    return null;
}

// Find previous sibling of particular class
function previousByClass(elem, cls) {
    while (elem = elem.previousElementSibling) {
        if (hasClass(elem, cls)) {
            return elem;
        }
    }
    return null;
}

// Sibling class found?
function hasClass(elem, cls) {
    let str = " " + elem.className + " ";
    let testCls = " " + cls + " ";
    return(str.indexOf(testCls) != -1) ;
}

CSS used for SIDEBAR:

/* Collapsable */
ul.toc > ul .treegroup:not(.is-expanded){
  display: none;
}

/* Chevron */
.chevron{
height:0.5rem;
width: 0.5rem;

}
.tree-expander{
  position: relative;
  cursor: pointer;
  user-select: none;
  display: block;
  padding-left: 0px;
  padding-top: 0px;
  padding-bottom: 0px;
}

.tree-indicator{
  display: inline-block;
  position: absolute;
  text-align: center;
  line-height: 16px;
  top: 6px;
  left: -1.5em;
  color: #5e5e5e;
  font-size: 0.6rem;
  transition: transform 0.15s ease-in-out;
  transform: rotate(0deg);
}

.treeitem.is-expanded > .tree-expander > .tree-indicator {
  transform: rotate(90deg);
}

Solution

  • Check expandEntryOnLoad for expanding the corresponding group. I assumed that in the end solution there will be no same links in different menus.

    For scrolling: Search for "scroll to element" and you should be able to implement it. :)

    Tip: Try to create more minimal, reproducible and runnable code snippets in your questions. That way people are more willing to help you, since it's less time consuming. Check this: I've been told to create a "runnable" example with "Stack Snippets", how do I do that?

    // Move this method to "tree". I just put it at the top so it's easy to find.
    function expandEntryOnLoad() {
      // Just for testing. Use the target below in production.
      let target = "/docs/people.html";
      // let target = window.location.pathname;
    
      // Find first "a" with the target as href
      let a = [...document.querySelectorAll(".toc a")].find(a => a.pathname === target);
      // Expand all tree group parents.
      if (a) {
        let parent = a;
        while (parent = parent.parentElement.closest(".treegroup")) parent.classList.add("is-expanded")
      }
    }
    
    // Find parent with given selector
    function parent_by_selector(elem, cls, stop_selector = 'body') {
      // NOTE: Simplified since there is already a function for that.
      return elem.closest("." + cls)
    };
    
    // Find next sibling of particular class
    function nextByClass(elem, cls) {
      while (elem = elem.nextElementSibling) {
        if (hasClass(elem, cls)) {
          return elem;
        }
      }
      return null;
    }
    
    // Find previous sibling of particular class
    function previousByClass(elem, cls) {
      while (elem = elem.previousElementSibling) {
        if (hasClass(elem, cls)) {
          return elem;
        }
      }
      return null;
    }
    
    // Sibling class found?
    function hasClass(elem, cls) {
      // NOTE: simplified, since there is an easier way to check this. You are already using it at several places.
      return elem.classList.contains(cls);
    }
    
    "use strict";
    
    function tree() {
      let menu = document.querySelector('.toc');
      let elements = menu.getElementsByClassName("treeitem");
      let sibling = null;
      let expanded = false;
    
      eventListeners();
    
      function eventListeners() {
        // Listen for click
        Array.from(elements).forEach(function(element) {
          element.addEventListener('click', function(ev) {
            let e = null;
            ev.target.classList.contains("treeitem") ? e = ev.target : e = parent_by_selector(ev.target, "treeitem");
            sibling = nextByClass(e, "treegroup")
    
            sibling.classList.contains('is-expanded') ? expanded = true : expanded = false;
            if (expanded) {
              e.classList.remove("is-expanded");
              sibling.classList.remove("is-expanded");
            } else {
              e.classList.add("is-expanded");
              sibling.classList.add("is-expanded");
            }
          }, false);
        });
      }
    
      expandEntryOnLoad();
    };
    
    // WAIT TILL DOCUMENT HAS LOADED BEFORE INITIATING FUNCTIONS
    document.addEventListener('DOMContentLoaded', tree());
    /* Collapsable */
    
    ul.toc>ul .treegroup:not(.is-expanded) {
      display: none;
    }
    
    
    /* Chevron */
    
    .chevron {
      height: 0.5rem;
      width: 0.5rem;
    }
    
    .tree-expander {
      position: relative;
      cursor: pointer;
      user-select: none;
      display: block;
      padding-left: 0px;
      padding-top: 0px;
      padding-bottom: 0px;
    }
    
    .tree-indicator {
      display: inline-block;
      position: absolute;
      text-align: center;
      line-height: 16px;
      top: 6px;
      left: -1.5em;
      color: #5e5e5e;
      font-size: 0.6rem;
      transition: transform 0.15s ease-in-out;
      transform: rotate(0deg);
    }
    
    .treeitem.is-expanded>.tree-expander>.tree-indicator {
      transform: rotate(90deg);
    }
    <ul class="toc is-vertically-scrollable has-flex-grow has-flex-shrink">
      <ul class="treegroup">
        <li class="none"><a href="/docs/level1.html">Level 1</a></li>
        <li class="none"><a href="/docs/level2.html">Level 2</a></li>
        <li class="treeitem"><span class="tree-expander"><span class="tree-indicator"><img src="/../docs/assets/images/chevron.png" class="chevron"></span>Level 3</span>
        </li>
        <ul class="treegroup">
          <li class="none"><a href="/docs/index.html">Home</a></li>
          <li class="none"><a href="/docs/about.html">About</a></li>
          <li class="treeitem"><span class="tree-expander"><span class="tree-indicator"><img src="/../docs/assets/images/chevron.png" class="chevron"></span>Level 3.2</span>
          </li>
          <ul class="treegroup">
            <li class="none"><a href="/docs/staff.html">Staff</a></li>
            <li class="treeitem"><span class="tree-expander"><span class="tree-indicator"><img src="/../docs/assets/images/chevron.png" class="chevron"></span>People</span>
            </li>
          </ul>
        </ul>
        <li class="none"><a href="/docs/level4.html">Level 4</a></li>
        <li class="treeitem"><span class="tree-expander"><span class="tree-indicator"><img src="/../docs/assets/images/chevron.png" class="chevron"></span>Level 5</span>
        </li>
        <ul class="treegroup">
          <li class="none"><a href="/docs/blog.html">Blog</a></li>
          <li class="treeitem"><span class="tree-expander"><span class="tree-indicator"><img src="/../docs/assets/images/chevron.png" class="chevron"></span>Level 5.2</span>
          </li>
          <ul class="treegroup">
            <li class="none"><a href="/docs/data-integration-and-etl/branches-and-loops-local.html">Branches &amp; Loops and everthing else in the world that is in between</a></li>
            <li class="none"><a href="/docs/people.html">People</a></li>
          </ul>
        </ul>
        <li class="none"><a href="/docs/level4.html">Level 6</a></li>
        <li class="treeitem"><span class="tree-expander"><span class="tree-indicator"><img src="/../docs/assets/images/chevron.png" class="chevron"></span>Level 7</span>
        </li>
        <ul class="treegroup">
          <li class="none"><a href="/docs/blog.html">Blog</a></li>
          <li class="treeitem"><span class="tree-expander"><span class="tree-indicator"><img src="/../docs/assets/images/chevron.png" class="chevron"></span>Level 5.2</span>
          </li>
          <ul class="treegroup">
            <li class="none"><a href="/docs/data-integration-and-etl/branches-and-loops-local.html">Branches &amp; Loops</a></li>
            <li class="none"><a href="/docs/people.html">People</a></li>
          </ul>
        </ul>
        <li class="none"><a href="/docs/level4.html">Level 8</a></li>
        <li class="treeitem"><span class="tree-expander"><span class="tree-indicator"><img src="/../docs/assets/images/chevron.png" class="chevron"></span>Level 9</span>
        </li>
        <ul class="treegroup">
          <li class="none"><a href="/docs/blog.html">Blog</a></li>
          <li class="treeitem"><span class="tree-expander"><span class="tree-indicator"><img src="/../docs/assets/images/chevron.png" class="chevron"></span>Level 5.2</span>
          </li>
          <ul class="treegroup">
            <li class="none"><a href="/docs/data-integration-and-etl/branches-and-loops-local.html">Branches &amp; Loops</a></li>
            <li class="none"><a href="/docs/people.html">People</a></li>
          </ul>
        </ul>
        <li class="none"><a href="/docs/level4.html">Level 10</a></li>
        <li class="treeitem"><span class="tree-expander"><span class="tree-indicator"><img src="/../docs/assets/images/chevron.png" class="chevron"></span>Level 11</span>
        </li>
        <ul class="treegroup">
          <li class="none"><a href="/docs/blog.html">Blog</a></li>
          <li class="treeitem"><span class="tree-expander"><span class="tree-indicator"><img src="/../docs/assets/images/chevron.png" class="chevron"></span>Level 5.2</span>
          </li>
          <ul class="treegroup">
            <li class="none"><a href="/docs/data-integration-and-etl/branches-and-loops-local.html">Branches &amp; Loops</a></li>
            <li class="none"><a href="/docs/people.html">People</a></li>
          </ul>
        </ul>
        <li class="none"><a href="/docs/level4.html">Level 12</a></li>
        <li class="treeitem"><span class="tree-expander"><span class="tree-indicator"><img src="/../docs/assets/images/chevron.png" class="chevron"></span>Level 13</span>
        </li>
        <ul class="treegroup">
          <li class="none"><a href="/docs/blog.html">Blog</a></li>
          <li class="treeitem"><span class="tree-expander"><span class="tree-indicator"><img src="/../docs/assets/images/chevron.png" class="chevron"></span>Level 5.2</span>
          </li>
          <ul class="treegroup">
            <li class="none"><a href="/docs/data-integration-and-etl/branches-and-loops-local.html">Branches &amp; Loops</a></li>
            <li class="none"><a href="/docs/people.html">People</a></li>
          </ul>
        </ul>
      </ul>
    </ul>