← All examples

JavaScript Navigation wikipedia.org

Wikipedia: collapsible article sections

Lets you click a second-level heading to collapse or expand the whole section of an article.

Code to copy

// Click any H2 heading to collapse or expand its section
function setupCollapse() {
  const headings = document.querySelectorAll('.mw-parser-output > .mw-heading2, .mw-parser-output > h2');
  headings.forEach(function (h) {
    if (h.dataset.jzCollapse) { return; }
    h.dataset.jzCollapse = '1';
    h.style.cursor = 'pointer';
    h.title = 'Click to collapse or expand this section';
    h.addEventListener('click', function (e) {
      if (e.target.tagName === 'A') { return; }
      let el = h.nextElementSibling;
      const hidden = h.dataset.jzHidden === '1';
      while (el && !/^H2$/.test(el.tagName) && !el.classList.contains('mw-heading2')) {
        el.style.display = hidden ? '' : 'none';
        el = el.nextElementSibling;
      }
      h.dataset.jzHidden = hidden ? '0' : '1';
      h.style.opacity = hidden ? '1' : '0.6';
    });
  });
}
setupCollapse();
new MutationObserver(setupCollapse).observe(document.body, { childList: true, subtree: true });

How to use this example

  1. Copy the code with the button above.
  2. Install JustZix (2 minutes) and open the extension on the target page.
  3. Add a new rule matching that page.
  4. Paste the code into the rule's JavaScript panel and save — it runs on every page visit.

Rate this example

No ratings yet — be the first.

Does this example work?

Snippets are useless without somewhere to paste them.

JustZix takes 2 minutes to install and runs your code on every matching page. No account, no payment.

Download free See use cases