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 isLargerThanMobile = window.matchMedia('screen and (min-width: 580px)').matches;
14 var sidebar = document.querySelector('.inline-toc');
15 var articleBody = document.querySelector('[itemprop="articleBody"]');
18 function addPermalink(el) {
19 el.classList.add('has-permalink');
20 var id = el.id || el.textContent.toLowerCase().replace(' ', '-');
21 el.insertAdjacentHTML('beforeend',
22 '<a class="permalink" title="Permalink" href="#' + id + '">#</a>');
25 // Add permalinks to heading elements.
26 function addPermalinkHeadings(container) {
28 ['h2','h3','h4'].forEach(function(h, i) {
29 [].forEach.call(container.querySelectorAll(h), addPermalink);
34 // Bomb out if we're not on an article page and have a TOC.
35 if (!(sidebar && articleBody)) {
39 if (isLargerThanMobile) {
40 var toc = sidebar.querySelector('#toc');
41 var offsetTop = sidebar.offsetParent.offsetTop
43 document.addEventListener('scroll', function(e) {
44 window.scrollY >= offsetTop ? sidebar.classList.add('sticky') :
45 sidebar.classList.remove('sticky');
48 toc.addEventListener('click', function(e) {
49 var parent = e.target.parentElement;
50 if (e.target.localName == 'a' && parent.classList.contains('toplevel')) {
51 // Allow normal link click if h2 toplevel heading doesn't have h3s.
52 if (parent.querySelector('.toc')) {
54 parent.classList.toggle('active');
60 // Prevent permalinks from appearong on mobile.
61 document.body.classList.add('no-permalink');
63 articleBody.addEventListener('click', function(e) {
64 if (e.target.localName == 'h2') {
65 e.target.parentElement.classList.toggle('active');
70 addPermalinkHeadings(articleBody);