picocss/docs/js/src/scrollspy.js

71 lines
1.6 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() {
new MostVisible()
},
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-07-09 18:18:39 +07:00
let links = document.querySelectorAll(this.targets.nav + ' a.' + this.targets.active);
2021-07-09 17:42:10 +07:00
links.forEach(function(link) {
2021-07-09 18:18:39 +07:00
link.classList.remove(this.targets.active);
2021-07-09 17:42:10 +07:00
}.bind(this));
// Set active state
2021-07-09 18:18:39 +07:00
let activeLink = document.querySelector(this.targets.nav + ' a[href="#' + currentSection + '"]');
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-07-10 10:47:57 +07:00
window.addEventListener('scroll', function(event) {
2021-07-09 17:42:10 +07:00
window.clearTimeout(isScrolling);
isScrolling = setTimeout(function() {
this.setActiveNav();
2021-07-09 18:18:39 +07:00
}.bind(this), this.interval);
2021-07-09 17:42:10 +07:00
}.bind(this), false);
}
}
2021-10-23 12:17:04 +07:00
export default scrollspy;