I would like share a esay dark mode with CSS and JavaScript
I continuos learn JS and CSS this a example using variables in CSS, and use Selectors, Events, Class in JS
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>Dark Mode</h1> <button id="app">Change the page color</button> </body> </html>
:root { --black: #000; --white: #fff; } *, *::after, *::before { margin: 0; padding: 0; box-sizing: border-box; } h1 { font-size: 50px; } #app { border: none; padding: 10px 20px; background-color: #ececec; color: var(--black); text-transform: uppercase; } .light { background-color: var(--white); color: var(--black); } .dark { background-color: var(--black); color: var(--white); }
let $btn = document.querySelector("#app"); // get button tag let $html = document.documentElement; // get html tag and the content let $body = document.body; // get body tag and the content let darkMode = getComputedStyle($html).getPropertyValue("--black"); // Here I get the value it has: CSS root let ligthMode = getComputedStyle($html).getPropertyValue("--white"); //Get the value that has: CSS root but in this case the color white $btn.addEventListener("click", (e) => { // Added a listener to the button if (e.type === "click") { // Evaluated the type of event that ran $body.classList.toggle("dark"); // Add a class } $body.classList.toggle("light"); // Remove a class });
I hope you like it, as a practice for handling the Document Object Model.
Top comments (0)