picocss/docs/js/src/scrollspy.js

80 lines
1.7 KiB
JavaScript
Raw Normal View History

2021-07-09 17:42:10 +07:00
/*
* Scrollspy
* Automatically update nav targets based on scroll position
*
* Require `most-visible.js` (https://github.com/andyexeter/most-visible)
*
* Pico.css - https://picocss.com
* Copyright 2019-2021 - Licensed under MIT
*/
2021-10-23 12:17:04 +07:00
import * as MostVisible from './most-visible.js';
2021-07-09 17:42:10 +07:00
export const scrollspy = {
2021-10-23 12:17:04 +07:00
mostVisible() {
2021-10-24 12:33:20 +07:00
new MostVisible();
2021-10-23 12:17:04 +07:00
},
2021-07-09 17:42:10 +07:00
// Config
2021-07-09 18:18:39 +07:00
minWidth: '992px',
interval: 75,
targets: {
2021-07-09 17:42:10 +07:00
sections: '[role="document"] > section',
nav: 'main aside nav',
active: 'active',
},
// Init
2021-09-12 10:58:05 +07:00
init() {
2021-07-09 18:18:39 +07:00
if (window.matchMedia('(min-width: ' + this.minWidth + ')').matches) {
2021-07-09 17:42:10 +07:00
this.setActiveNav();
this.scrollStop();
}
},
// Set active section in nav
setActiveNav() {
// Get active section
2021-09-12 10:58:05 +07:00
let currentSection = mostVisible(this.targets.sections).getAttribute('id');
2021-07-09 17:42:10 +07:00
// Remove all active states
2021-10-24 12:33:20 +07:00
let links = document.querySelectorAll(
this.targets.nav + ' a.' + this.targets.active
);
links.forEach(
function (link) {
link.classList.remove(this.targets.active);
}.bind(this)
);
2021-07-09 17:42:10 +07:00
// Set active state
2021-10-24 12:33:20 +07:00
let activeLink = document.querySelector(
this.targets.nav + ' a[href="#' + currentSection + '"]'
);
2021-07-09 18:18:39 +07:00
activeLink.classList.add(this.targets.active);
2021-07-09 17:42:10 +07:00
// Open details parent
activeLink.closest('details').setAttribute('open', '');
},
// Scroll stop
scrollStop() {
let isScrolling;
2021-10-24 12:33:20 +07:00
window.addEventListener(
'scroll',
function (event) {
window.clearTimeout(isScrolling);
isScrolling = setTimeout(
function () {
this.setActiveNav();
}.bind(this),
this.interval
);
}.bind(this),
false
);
},
};
2021-10-23 12:17:04 +07:00
2021-10-24 12:33:20 +07:00
export default scrollspy;