DEV Community

Mauricio Yair
Mauricio Yair

Posted on

1 3

Easy Mode Dark

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>
Enter fullscreen mode Exit fullscreen mode
 :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);
}
Enter fullscreen mode Exit fullscreen mode
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
});
Enter fullscreen mode Exit fullscreen mode

I hope you like it, as a practice for handling the Document Object Model.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs