1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
7 // Switches the sidebar between floating on the left and position:fixed
8 // depending on whether it's scrolled into view, and manages the scroll-to-top
9 // button: click logic, and when to show it.
12 var isLargerThanMobileQuery =
13 window.matchMedia('screen and (min-width: 581px)');
15 var sidebar = document.querySelector('.inline-toc');
16 var sidebarOffsetTop = null;
17 var articleBody = document.querySelector('[itemprop="articleBody"]');
19 // Bomb out unless we're on an article page and have a TOC.
20 if (!(sidebar && articleBody)) {
24 function addPermalink(el) {
25 el.classList.add('has-permalink');
26 var id = el.id || el.textContent.toLowerCase().replace(' ', '-');
27 el.insertAdjacentHTML('beforeend',
28 '<a class="permalink" title="Permalink" href="#' + id + '">#</a>');
31 // Add permalinks to heading elements.
32 function addPermalinkHeadings(container) {
34 ['h2','h3','h4'].forEach(function(h, i) {
35 [].forEach.call(container.querySelectorAll(h), addPermalink);
40 function onScroll(e) {
41 window.scrollY >= sidebarOffsetTop ? sidebar.classList.add('sticky') :
42 sidebar.classList.remove('sticky');
45 function onMediaQuery(e) {
47 // On tablet & desktop, show permalinks, manage TOC position.
48 document.body.classList.remove('no-permalink');
49 sidebarOffsetTop = sidebar.offsetParent.offsetTop
50 document.addEventListener('scroll', onScroll);
52 // On mobile, hide permalinks. TOC is hidden, doesn't need to scroll.
53 document.body.classList.add('no-permalink');
54 document.removeEventListener('scroll', onScroll);
58 // Toggle collapsible sections (mobile).
59 articleBody.addEventListener('click', function(e) {
60 if (e.target.localName == 'h2' && !isLargerThanMobileQuery.matches) {
61 e.target.parentElement.classList.toggle('active');
65 sidebar.querySelector('#toc').addEventListener('click', function(e) {
66 var parent = e.target.parentElement;
67 if (e.target.localName == 'a' && parent.classList.contains('toplevel')) {
68 // Allow normal link click if h2 toplevel heading doesn't have h3s.
69 if (parent.querySelector('.toc')) {
71 parent.classList.toggle('active');
76 // Add +/- expander to headings with subheading children.
77 [].forEach.call(toc.querySelectorAll('.toplevel'), function(heading) {
78 if (heading.querySelector('.toc')) {
79 heading.firstChild.classList.add('hastoc');
83 isLargerThanMobileQuery.addListener(onMediaQuery);
84 onMediaQuery(isLargerThanMobileQuery);
86 addPermalinkHeadings(articleBody);