Question:
How to do light and dark mode in a website using HTML and JavaScript?

Problem:

I tried to have 2 buttons, one changing the bgcolor of body to white, the other to black (i want a light mode and dark mdeo for my website)


Right now it does not change the color of the background


This is my html code:

<button onclick="light_mode()">Light mode</button>

<button onclick="dark_mode()">Dark mode</button>


this is my javascript:

function dark_mode() {

        document.getElementById('body').x.style.background = "color:black";

    }

    function light_mode() {

        document.getElementById('body').x.style.background = "color:white";

    }


I gave the body an id "body" so the js would work. Right now it does not work though. Im a beginner at javascript so pls simple explanation. Thank you!


Solution:

The way you're doing the changing of the colours is a bit off. Here's a corrected version of your JavaScript:

function dark_mode() {

    document.getElementById('body').style.backgroundColor = "black";

}


function light_mode() {

    document.getElementById('body').style.backgroundColor = "white";

}


And, your HTML should look something like this:

<body id="body">

    <!-- Your content goes here -->


    <button onclick="light_mode()">Light mode</button>

    <button onclick="dark_mode()">Dark mode</button>


    <!-- More content if you have -->

</body>


Be sure to let me know if you have any other questions :)


Suggested blogs:

>Building Web API using ASP.NET (C#)

>Built Web API using ASP.NET (C#)

>Built your simple Android App with Kotlin

>How to manage the Text in the container in Django?

>Activating Virtual environment in visual studio code windows 11

>Fix webapp stops working issue in Django- Python webapp

>Creating a form in Django to upload a picture from website

>Sending Audio file from Django to Vue


Ritu Singh

Ritu Singh

Submit
0 Answers