mirror of
https://github.com/dgtlmoon/changedetection.io.git
synced 2026-06-06 20:07:35 +00:00
80 lines
2.3 KiB
JavaScript
80 lines
2.3 KiB
JavaScript
/**
|
|
* sub-tabs.js — Vertical sub-tab switcher.
|
|
*
|
|
* Finds every .stab-shell on the page and wires up tab switching.
|
|
* The shell needs an id= attribute for localStorage persistence.
|
|
*
|
|
* HTML contract (generated by _stab.html macros):
|
|
* .stab-shell#some-id
|
|
* .stab-nav
|
|
* button.stab-btn[data-stab="foo"]
|
|
* .stab-body
|
|
* .stab-pane[data-stab="foo"]
|
|
*
|
|
* Any element inside the shell with data-stab-goto="tab-id" triggers
|
|
* navigation to that pane when clicked (for CTA buttons etc.).
|
|
*/
|
|
|
|
(function () {
|
|
'use strict';
|
|
|
|
function initShell(shell) {
|
|
var shellId = shell.id;
|
|
var storageKey = shellId ? 'stab:' + shellId : null;
|
|
|
|
var btns = Array.prototype.slice.call(shell.querySelectorAll('.stab-nav .stab-btn'));
|
|
var panes = Array.prototype.slice.call(shell.querySelectorAll('.stab-body .stab-pane'));
|
|
|
|
if (!btns.length || !panes.length) return;
|
|
|
|
var validIds = btns.map(function (b) { return b.dataset.stab; });
|
|
|
|
function activate(tabId) {
|
|
if (validIds.indexOf(tabId) === -1) return;
|
|
|
|
btns.forEach(function (b) {
|
|
b.classList.toggle('active', b.dataset.stab === tabId);
|
|
});
|
|
panes.forEach(function (p) {
|
|
p.classList.toggle('active', p.dataset.stab === tabId);
|
|
});
|
|
|
|
if (storageKey) {
|
|
try { localStorage.setItem(storageKey, tabId); } catch (e) {}
|
|
}
|
|
}
|
|
|
|
// Nav button clicks
|
|
btns.forEach(function (btn) {
|
|
btn.addEventListener('click', function () { activate(btn.dataset.stab); });
|
|
});
|
|
|
|
// data-stab-goto navigation from CTA buttons anywhere inside the shell
|
|
shell.addEventListener('click', function (e) {
|
|
var el = e.target.closest('[data-stab-goto]');
|
|
if (el && shell.contains(el)) {
|
|
e.preventDefault();
|
|
activate(el.dataset.stabGoto);
|
|
}
|
|
});
|
|
|
|
// Restore persisted tab or fall back to first tab
|
|
var stored = null;
|
|
if (storageKey) {
|
|
try { stored = localStorage.getItem(storageKey); } catch (e) {}
|
|
}
|
|
activate(stored && validIds.indexOf(stored) !== -1 ? stored : validIds[0]);
|
|
}
|
|
|
|
function initAll() {
|
|
var shells = document.querySelectorAll('.stab-shell');
|
|
shells.forEach(function (shell) { initShell(shell); });
|
|
}
|
|
|
|
if (document.readyState === 'loading') {
|
|
document.addEventListener('DOMContentLoaded', initAll);
|
|
} else {
|
|
initAll();
|
|
}
|
|
}());
|