Files
infomate.club/static/js/main.js
Konstantin Mikhailov 404ee080a6 Fix for white flashes (#3)
* Detect dark mode in CSS

We duplicated css code a bit but instead users won't see white flashes
when they navigate around the site. Also as the result might be able to
override their system-wide dark mode settings with the theme switcher.

* Apply theme attribute as early as possible

This change resolves the flashing issue for visitors who used theme
switcher.
2020-01-10 20:26:58 +01:00

59 lines
1.5 KiB
JavaScript

function initializeThemeSwitcher() {
const themeSwitch = document.querySelector('.theme-switcher input[type="checkbox"]');
themeSwitch.addEventListener("change", function(e) {
let theme = 'light';
if (e.target.checked) {
theme = 'dark';
}
document.documentElement.setAttribute('theme', theme);
localStorage.setItem('theme', theme);
}, false);
const theme = localStorage.getItem('theme');
if (theme !== null) {
themeSwitch.checked = (theme === 'dark');
}
}
function hideTooltip() {
let visibleTooltips = document.querySelectorAll(".article-tooltip");
for (let i = 0; i < visibleTooltips.length; i++) {
if (visibleTooltips[i].style.display !== "none") {
visibleTooltips[i].style.display = null;
}
}
}
function hideTooltipOnAnyClick() {
document.body.addEventListener("click", function(e) {
hideTooltip();
}, true);
}
function checkKeyPress(e) {
let tooltip;
if (e.keyCode == 81) {
tooltip = document.activeElement.parentNode.parentNode.querySelector('.article-tooltip');
if (tooltip.style.display == "block") {
tooltip.style.display = null;
} else {
tooltip.style.display = "block";
}
}
if (e.keyCode == 9) {
hideTooltip();
}
}
let body = document.querySelector('body');
body.addEventListener('keyup', checkKeyPress);
initializeThemeSwitcher();
hideTooltipOnAnyClick();