UNPKG

1.91 kBJavaScriptView Raw
1/*!
2 * Scrollspy
3 * Automatically update nav targets based on scroll position
4 *
5 * Require `most-visible.js` from https://github.com/andyexeter/most-visible
6 *
7 * Pico.css - https://picocss.com
8 * Copyright 2019 - Licensed under MIT
9 */
10
11(function() {
12
13 /**
14 * Config
15 */
16 var scrollspy = {
17 interval: 75, // Delay for detect scroll stop
18 sections: '[role="document"] > section', // Target for sections
19 nav: 'main aside nav', // Target for nav
20 active: 'active', // .class for active element
21 };
22
23
24
25 /**
26 * Init
27 */
28
29 if (window.matchMedia("(min-width: 992px)").matches) {
30 activeNav();
31
32 scrollStop(
33 function () {
34 activeNav()
35 }
36 );
37 }
38
39
40
41 /**
42 * Set active section in nav
43 */
44
45 function activeNav() {
46
47 // Get active section
48 var section = mostVisible(scrollspy.sections).getAttribute('id');
49
50 // Remove all active states
51 var allActive = document.querySelectorAll(scrollspy.nav + ' a.' + scrollspy.active);
52 for (var i = 0; i < allActive.length; i++) {
53 allActive[i].classList.remove(scrollspy.active);
54 }
55
56 // Set active state
57 var active = document.querySelector(scrollspy.nav + ' a[href="#' + section + '"]');
58 active.classList.add(scrollspy.active);
59
60 // Open details parent
61 active.parentNode.parentNode.parentNode.setAttribute('open', '');
62 }
63
64
65
66 /**
67 * Scroll stop
68 * Detect when the user stop scrolling
69 * Source: https://vanillajstoolkit.com/helpers/scrollstop/
70 *
71 * @param {Function} callback The function to run after scrolling
72 *
73 */
74
75 function scrollStop(callback) {
76 var isScrolling;
77 window.addEventListener('scroll', function (event) {
78 window.clearTimeout(isScrolling);
79 isScrolling = setTimeout(function() {
80 callback();
81 }, scrollspy.interval);
82 }, false);
83 }
84
85})();