Upstream version 5.34.92.0
[platform/framework/web/crosswalk.git] / src / chrome / common / extensions / docs / static / js / article.js
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.
4
5 // Scroll handling.
6 //
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.
10 (function() {
11
12 var isLargerThanMobile = window.matchMedia('screen and (min-width: 580px)').matches;
13
14 var sidebar = document.querySelector('.inline-toc');
15 var articleBody = document.querySelector('[itemprop="articleBody"]');
16
17
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>');
23 }
24
25 // Add permalinks to heading elements.
26 function addPermalinkHeadings(container) {
27   if (container) {
28     ['h2','h3','h4'].forEach(function(h, i) {
29       [].forEach.call(container.querySelectorAll(h), addPermalink);
30     });
31   }
32 }
33
34 // Bomb out if we're not on an article page and have a TOC.
35 if (!(sidebar && articleBody)) {
36   return;
37 }
38
39 if (isLargerThanMobile) {
40   var toc = sidebar.querySelector('#toc');
41   var offsetTop = sidebar.offsetParent.offsetTop
42
43   document.addEventListener('scroll', function(e) {
44     window.scrollY >= offsetTop ? sidebar.classList.add('sticky') :
45                                   sidebar.classList.remove('sticky');
46   });
47
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')) {
53         e.preventDefault();
54         parent.classList.toggle('active');
55       }
56     }
57   });
58
59 } else {
60   // Prevent permalinks from appearong on mobile.
61   document.body.classList.add('no-permalink');
62
63   articleBody.addEventListener('click', function(e) {
64     if (e.target.localName == 'h2') {
65       e.target.parentElement.classList.toggle('active');
66     }
67   });
68 }
69
70 addPermalinkHeadings(articleBody);
71
72 }());