Add dark mode toggle

This commit is contained in:
Jake Howard 2022-08-20 15:31:14 +01:00
parent e0998c7ed8
commit 727ad725d1
Signed by: jake
GPG key ID: 57AFB45680EDD477
3 changed files with 36 additions and 8 deletions

View file

@ -1,9 +1,13 @@
const DARK_MODE_CLASS = "dark-mode"; const DARK_MODE_CLASS = "dark-mode";
const STORAGE_KEY = "dark-mode";
const body = document.getElementsByTagName("body")[0]; const body = document.getElementsByTagName("body")[0];
const darkModeToggle = document.getElementById("dark-mode-toggle");
const matchesDarkMode = window.matchMedia("(prefers-color-scheme: dark)"); const matchesDarkMode = window.matchMedia("(prefers-color-scheme: dark)");
function handleDarkMode(darkMode) { function handleDarkMode(darkMode) {
window.localStorage.setItem(STORAGE_KEY, darkMode.toString());
if (darkMode) { if (darkMode) {
body.classList.add(DARK_MODE_CLASS); body.classList.add(DARK_MODE_CLASS);
} else { } else {
@ -11,8 +15,19 @@ function handleDarkMode(darkMode) {
} }
} }
matchesDarkMode.addEventListener("change", (event) => if (window.localStorage.getItem(STORAGE_KEY) === null) {
handleDarkMode(event.matches) window.localStorage.setItem(STORAGE_KEY, matchesDarkMode.matches);
); handleDarkMode(matchesDarkMode.matches);
} else {
handleDarkMode(window.localStorage.getItem(STORAGE_KEY) === "true");
}
handleDarkMode(matchesDarkMode.matches); window.addEventListener("load", () => {
matchesDarkMode.addEventListener("change", (event) =>
handleDarkMode(event.matches)
);
darkModeToggle.addEventListener("click", () => {
handleDarkMode(window.localStorage.getItem(STORAGE_KEY) !== "true");
});
});

View file

@ -6,3 +6,11 @@
color: $white; color: $white;
} }
} }
#dark-mode-toggle i {
transition: transform 0.3s;
@include dark-mode {
transform: rotate(180deg);
}
}

View file

@ -22,14 +22,19 @@
{% endfor %} {% endfor %}
</div> </div>
{% if search_page %} <div class="navbar-end is-hidden-touch mr-2">
<div class="navbar-end is-hidden-touch mr-2"> <a class="navbar-item navbar-icon is-link" id="dark-mode-toggle">
<span class="icon">
<i class="fa-solid fa-circle-half-stroke" aria-hidden="true"></i>
</span>
</a>
{% if search_page %}
<a class="navbar-item navbar-icon" href="{% pageurl search_page %}"> <a class="navbar-item navbar-icon" href="{% pageurl search_page %}">
<span class="icon"> <span class="icon">
<i class="fas fa-search" aria-hidden="true"></i> <i class="fas fa-search" aria-hidden="true"></i>
</span> </span>
</a> </a>
</div> {% endif %}
{% endif %} </div>
</div> </div>
</nav> </nav>