Fix navbar style on page reloads and theme updates

This commit is contained in:
Mark Dumay
2024-02-11 08:28:16 +01:00
parent 7c3aed4822
commit 9e52107dbf

View File

@@ -3,14 +3,7 @@ const togglers = document.querySelectorAll('.main-nav-toggler')
const modeSelectors = document.querySelectorAll('.switch-mode-collapsed')
const colorsBG = ['body', 'secondary', 'tertiary']
if (navbar !== null && togglers !== null) {
// initialize background color
const color = (navbar.getAttribute('data-navbar-color') || 'body')
const bg = colorsBG.includes(color) ? `var(--bs-${color}-bg)` : `var(--bs-navbar-color-${color})`
navbar.style.setProperty('--bs-navbar-expanded-color', bg)
// set the navbar background color to opaque when scrolling past a breakpoint
window.onscroll = () => {
function updateNavbar () {
if (window.scrollY > 75) {
navbar.classList.add('nav-active')
const storedTheme = localStorage.getItem('theme')
@@ -22,6 +15,34 @@ if (navbar !== null && togglers !== null) {
}
}
if ((navbar !== null) && (window.performance.getEntriesByType)) {
if (window.performance.getEntriesByType('navigation')[0].type === 'reload') {
updateNavbar()
}
}
if (navbar !== null && togglers !== null) {
// observe state changes to the site's color mode
const html = document.querySelector('html')
const config = {
attributes: true,
attributeFilter: ['data-bs-theme']
}
const Observer = new MutationObserver((mutationrecords) => {
updateNavbar()
})
Observer.observe(html, config)
// initialize background color
const color = (navbar.getAttribute('data-navbar-color') || 'body')
const bg = colorsBG.includes(color) ? `var(--bs-${color}-bg)` : `var(--bs-navbar-color-${color})`
navbar.style.setProperty('--bs-navbar-expanded-color', bg)
// set the navbar background color to opaque when scrolling past a breakpoint
window.onscroll = () => {
updateNavbar()
}
// set the navbar background color to opaque when expanded
for (let i = 0; i < togglers.length; ++i) {
togglers[i].onclick = () => {