Switch between including 'light' or 'dark' styles using Javascript?

I am currently working on a project where I aim to incorporate a dark mode toggle feature. To maintain organization and scalability, I have chosen to implement the SASS (.scss) architecture rather than plain CSS.

My plan is to utilize variables within my .scss files for both light mode (such as $white for background and $black for text color) and dark mode (e.g. $black for background and $white for text color). By selectively importing either of these modes in my main.scss file through @import, I hope to achieve the desired dark mode effect.

In essence, I am seeking assistance with creating a JavaScript script that will allow me to dynamically switch between '@import 'dark'' and '@import 'light'' within my main.scss file at the press of a button.

This means that upon toggling to dark mode, the line in my main.scss file referring to the import will change from '@import 'light'' to '@import 'dark'', and vice versa.

If anyone can offer guidance or support on this matter, it would be greatly appreciated as I have been struggling with finding a solution to this challenge for quite some time now.

Answer №1

Regrettably, I do not have much expertise in sass, but it is feasible to implement light and dark modes solely using html, css, and js.

const inputEl = document.querySelector(".input");

const bodyEl = document.querySelector("body");

inputEl.checked = updateBody();

function updateBody() {
    if (inputEl.checked) {
        bodyEl.style.background = "black";
    } else {
        bodyEl.style.background = "white";
    }
}

inputEl.addEventListener("input", ()=>{
    updateBody();
    
});
body {
    margin: 0;
    display: flex;
    justify-content: center;
    height: 100vh;
    align-items: center;
    transition: .4s;
}

.label {
    width: 80px;
    height: 40px;
    background-color: lightgray;
    position: absolute;
    border-radius: 20px;
    cursor: pointer;
}

.input {
    visibility: hidden;
    /* z-index: 1; */
}

.circle {
    width: 34px;
    background-color: white;
    height: 34px;
    border-radius: 50%;
    top: 3px;
    position: absolute;
    left: 3px;
    animation: toggleOff 0.4s linear forwards;
}

.input:checked + .label {
    background-color: white;
}

.input:checked + .label .circle {
    animation: toggleOn 0.4s linear forwards;
    background-color: black;
}

@keyframes toggleOn {
    0%{
        transform: translateX(0);
    }
    100%{
        transform: translateX(40px);
    }
    
}

@keyframes toggleOff {
    0%{
        transform: translateX(40px);</answer1>
<exanswer1><div class="answer" i="75590466" l="4.0" c="1677567765" a="S2VtaSBDaHJpcw==" ai="19573438">
<p>I don't really know much about sass, but you can achieve the light and dark mode with just html, css and js.</p>
<p><div>
<div>
<pre class="lang-js"><code>const inputEl = document.querySelector(".input");

const bodyEl = document.querySelector("body");

inputEl.checked = updateBody();

function updateBody() {
    if (inputEl.checked) {
        bodyEl.style.background = "black";
    } else {
        bodyEl.style.background = "white";
    }
}

inputEl.addEventListener("input", ()=>{
    updateBody();
    
});
body {
    margin: 0;
    display: flex;
    justify-content: center;
    height: 100vh;
    align-items: center;
    transition: .4s;
}

.label {
    width: 80px;
    height: 40px;
    background-color: lightgray;
    position: absolute;
    border-radius: 20px;
    cursor: pointer;
}

.input {
    visibility: hidden;
    /* z-index: 1; */
}

.circle {
    width: 34px;
    background-color: white;
    height: 34px;
    border-radius: 50%;
    top: 3px;
    position: absolute;
    left: 3px;
    animation: toggleOff 0.4s linear forwards;
}

.input:checked + .label {
    background-color: white;
}

.input:checked + .label .circle {
    animation: toggleOn 0.4s linear forwards;
    background-color: black;
}

@keyframes toggleOn {
    0%{
        transform: translateX(0);
    }
    100%{
        transform: translateX(40px);
    }
    
}

@keyframes toggleOff {
    0%{
        transform: translateX(40px);
    }
    100%{
        transform: translateX(0);
    }
    
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">>
    <title>Dark Mode Toggle</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <input type="checkbox"  id="dark-mode" class="input">
    <label for="dark-mode" class="label">
        <div class="circle"></div>
    </label>
   
</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Measure with an "em" unit indicated by a dot

Could you clarify if there is a distinction between writing padding:.6em and padding:0.6em; and if they have the same value, why not just use padding:0.6em; ? Thank you ...

Can integer values be stored in localStorage similar to JavaScript objects and retrieved without requiring typecasting?

After setting an integer value to a localStorage item: localStorage.setItem('a', 1) and checking its data type: typeof(localStorage.a) "string" it shows as a string. I then typecast it to an int for my purposes: parseInt(localStorage.a) My ...

Struggling with getting my Vue-CLI app deployed on Heroku

After diligently following all the steps outlined in this tutorial: https://codeburst.io/quick-n-clean-way-to-deploy-vue-webpack-apps-on-heroku-b522d3904bc8 I encountered an error message when checking my app at: The error indicated: Method Not Allowed ...

Alter the properties based on the size of the window

I am working with React-Spring and I need to adjust the offset of a component when the window size changes. I attempted the following solution, but it is not functioning correctly and requires me to refresh the browser each time. <ParallaxLayer ...

Sending information to @select of multiselect in Vue.js - vue-multiselect

I'm currently working on passing a parameter to the @select event function in Vue.js HTML <template> <div class="container"> <div v-for="(billItem, k) in billItems" :key="k" > <div class=&q ...

What is the process for creating a React Component with partially applied props?

I am struggling with a function that takes a React component and partially applies its props. This approach is commonly used to provide components with themes from consumers. Essentially, it transforms <FancyComponent theme="black" text="blah"/> int ...

What is the best way to retrieve a specific value from a JSON file using a numerical identifier?

Imagine a scenario where there is a JSON file structured like this: { "data": [ { "id": "1", "name": "name1" }, { "id": "2", "name": "name2" } ] } If you know the ...

What is the best way to link JavaScript files from a Grails plugin in a separate Grails application?

I have developed a unique plugin that offers multiple Grails controllers and domain objects. Additionally, I have created several AngularJS UI components that I wish to utilize in various other projects. These specific files are located within the web-app ...

XPath allows for the selection of both links and anchors on a webpage

Currently, I am using Screaming Frog and seeking to utilize XPath for a specific task. My objective is to extract all links and anchors that contain a certain class within the main body content, excluding any links found within div.list. I have attempted ...

Adjust the alignment of text to a precise vertical ratio of the image

Let's say I have this amazing logo with some artistic text in it that cannot be replicated using a downloaded WebFont In the image, the text baseline sits at 68% from the top and 32% from the bottom. Now I want to align text in an HTML document, whi ...

Tips for creating spacing between an image and a button when utilizing the routerLink feature in CSS

To enhance the user interface, I've utilized a routerLink with an image to navigate back to the home page, and a button to direct users to add a new customer. Now, I am aiming to create some space between these elements. Previously, I used "& ...

Error occurs in Query component when using a higher order component (HOC) due to element type

I've developed a custom higher-order component called withInfiniteScroll, designed to enable infinite scrolling functionality for a basic list of data. My aim is to integrate this HOC within Apollo's Query component, but I'm encountering an ...

Is it possible to utilize $(this) within the $.post() function?

I seem to be having trouble accessing $(this) from inside the $.post section. It works perfectly fine outside of it. Here is the JavaScript code: $('.idea').each(function(){ var title = $(this).html(); $.post("votes.php", { t ...

Discover the sequence that is the smallest in lexicographical order possible

Here is the question at hand Given a sequence of n integers arr, find the smallest possible lexicographic sequence that can be obtained after performing a maximum of k element swaps, where each swap involves two consecutive elements in the sequence. Note: ...

Why isn't the unit test passing when it clearly should be?

I am encountering an issue with testing a simple function that I have created. Despite the fact that the function works correctly in practice, it is not being tested properly... Explanation of how my function operates (While it functions as intended, the ...

Incorporate a JSON file into the Webpack output separately from the bundle.js file

Is there a way for my webpack application to read a JSON file at runtime without including it in the bundle.js after packaging? I want the JSON file to be available in the package folder but not bundled with the rest of the code. How can I achieve this? ...

Animate the entrance of mobile content as it slides into view while scrolling

I am currently working on a WordPress theme and facing an issue: When I click the hamburger menu without scrolling down the page, the mobile menu slides in smoothly. However, if I scroll down the page, the mobile menu fails to slide into view (I have to s ...

How can I prevent an HTML element from losing focus?

Currently, I am developing an online editor that requires accurate character inputs. To achieve this, I have implemented the jQuery.onKeyPress event on a textarea element. This approach was chosen because obtaining character inputs from the body directly p ...

Step-by-step guide to building multiple layouts in React.js using react-router-dom

For my new web application, I am looking to create two distinct layouts based on the user type. If the user is an admin, they should see the dashboard layout, while employees should be directed to the form layout. Initially, only the login page will be dis ...

Is there a more efficient way to optimize my coding for this Cellular Automata project?

As a beginner in programming, I wanted to delve into the world of cellular automata and decided to create my own using JavaScript. The project involves a simple binary (black and white) 2D CA where each cell updates its color based on the colors of its 8 ...