User:Knightmare/common.js

From ARMCO
Jump to navigation Jump to search

Note: After saving, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Go to Menu → Settings (Opera → Preferences on a Mac) and then to Privacy & security → Clear browsing data → Cached images and files.
(function() {
    // Find the TOC element
    var toc = document.getElementById('toc');
    if (!toc) return;  // If no TOC, exit

    // Grab all headers in the page (h2, h3, h4, etc.)
    var headers = document.querySelectorAll('h2, h3, h4, h5, h6');
    var tocLinks = toc.querySelectorAll('li');

    // Create a function to organize headers into a nested structure
    function organizeToc() {
        var lastLevel = 2;  // Default TOC starts from h2
        var stack = [];  // Used to track the nested structure

        // Iterate over all headers and organize them by header level
        headers.forEach(function(header, index) {
            var level = parseInt(header.tagName[1]);  // Get level from the header tag (h2 -> 2)

            // Find the corresponding TOC list item for this header
            var tocItem = tocLinks[index];

            // If this header is of a higher level, add it to the current stack
            if (level > lastLevel) {
                stack.push(tocItem);
            }
            // If this header is at the same or lower level, pop the stack back to the right level
            else if (level < lastLevel) {
                stack = stack.slice(0, level - 2);
            }

            // If we're nesting, append the toc item to the last item in the stack
            if (stack.length > 0) {
                var parentItem = stack[stack.length - 1];
                var sublist = parentItem.querySelector('ul');
                if (!sublist) {
                    sublist = document.createElement('ul');
                    parentItem.appendChild(sublist);
                }
                sublist.appendChild(tocItem);
            }

            // Push the current item onto the stack
            stack.push(tocItem);

            // Update the last level
            lastLevel = level;
        });
    }

    // Run the TOC nesting function
    organizeToc();
})();