checkbox out html attr in

This commit is contained in:
Pagwin 2025-01-03 22:18:11 -05:00
parent 17e91f649c
commit 7ba394a5d2
No known key found for this signature in database
GPG key ID: 81137023740CA260
4 changed files with 10 additions and 23 deletions

View file

@ -18,15 +18,6 @@
to work without Javascript
-->
<form action="" method="post">
<!--
id present so service worker shenanigans are
more durable and css has something to latch
onto
hidden because the user should never see this
checkbox
-->
<input id="css_state" type="checkbox" hidden>
<!--
hidden because if a user agent doesn't support
CSS we don't want to show the light-dark toggle

View file

@ -1,13 +1,7 @@
"use strict";
const toggle_button = document.body.querySelector("#light_dark_toggle");
const css_state_checkbox = document.body.querySelector("#css_state");
// this does nothing but I was hoping it would let my LSP figure out
// that css_state_checkbox is an input element so the remaining code
// is valid
// Real use case might still find this useful as self documenting code
console.assert(css_state_checkbox instanceof HTMLInputElement);
const root = document.body.parentElement;
toggle_button.addEventListener("click", (event) => {
@ -15,7 +9,9 @@ toggle_button.addEventListener("click", (event) => {
event.preventDefault();
const theme_toggled = !css_state_checkbox.checked;
// !== could be used but the check is to see if the attribute is "true"
// this writing is intend to make that clearer
const theme_toggled = !(root.getAttribute("toggletheme")?.at(0) === "t");
// set the cookie so backend/service worker can do it's thing
// cookies have other options you may wanna set especially
@ -24,7 +20,7 @@ toggle_button.addEventListener("click", (event) => {
document.cookie = `theme_toggled=${theme_toggled}`;
css_state_checkbox.checked = theme_toggled;
root.setAttribute("toggletheme", theme_toggled);
});
// If you wanna implement this for a site with a backend

View file

@ -7,7 +7,7 @@
--background-color: black;
--text-color: white;
}
:root:has(#css_state:checked){
:root[toggletheme="true"]{
--background-color: white;
--text-color: black;
}
@ -17,7 +17,7 @@
--background-color: white;
--text-color: black;
}
:root:has(#css_state:checked){
:root[toggletheme="true"]{
--background-color: black;
--text-color: white;
}

View file

@ -18,9 +18,9 @@ async function fetchResponse(event) {
}
theme_toggled = value[0] === "t";
}
// this is a brittle way of accomplishing our desired behavior
body.replace(`<input id="css_state" type="checkbox" hidden>`,
`<input id="css_state" type="checkbox" hidden ${theme_toggled ? "checked" : ""}>`);
// this is a somewhat brittle way of accomplishing our desired behavior
body.replace(`<html lang="en">`,
`<html lang="en" toggletheme="${theme_toggled}">`);
console.log(body);
return new Response(body, resp);
}