site.lyte.dev/static/global.js

60 lines
1.8 KiB
JavaScript

const body = document.body
const queryAll = sel => document.querySelectorAll(sel)
const initTheme = () => {
const curTheme = localStorage.getItem('theme')
const oldTheme = curTheme == 'dark' ? 'light' : 'dark'
body.classList.add(`${curTheme}-theme`)
body.classList.remove(`${oldTheme}-theme`)
}
if (localStorage.getItem('theme') === null) {
localStorage.setItem('theme', window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')
}
initTheme()
const toggleTheme = ev => {
localStorage.setItem('theme', localStorage.getItem('theme') == 'dark' ? 'light' : 'dark')
initTheme()
if (!!ev.target) ev.preventDefault()
return false
}
queryAll('.theme-toggler').forEach(a => a.addEventListener('click', toggleTheme))
queryAll('.js-only').forEach(a => a.classList.remove('js-only'))
queryAll('.js-disabled-only').forEach(a => a.remove())
const initAlign = () => {
const cur = localStorage.getItem('align')
const prev = cur == 'center' ? 'left' : 'center'
body.classList.add('align-' + cur)
body.classList.remove('align-' + prev)
}
if (localStorage.getItem('align') === null) localStorage.setItem('align', 'center')
initAlign()
const toggleAlign = ev => {
localStorage.setItem('align', localStorage.getItem('align') == 'center' ? 'left' : 'center')
initAlign()
if (!!ev.target) ev.preventDefault()
return false
}
queryAll('.align-toggler').forEach(a => a.addEventListener('click', toggleAlign))
window.addEventListener('load', _ev => {
console.log('loaded')
const selector = [1, 2, 3, 4, 5, 6].map(n => `h${n}[id]`).join(',')
console.log(selector)
queryAll(selector).forEach(el => {
console.log(el)
const anchorLink = document.createElement('a')
anchorLink.classList.add('anchor-link')
anchorLink.textContent = '§'
anchorLink.href = `#${el.id}`
el.appendChild(anchorLink)
})
})