Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 3812

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 61k
Author
Asked: November 26, 20242024-11-26T06:10:07+00:00 2024-11-26T06:10:07+00:00

How to add dark mode using javascript

  • 61k

We're going to be adding dark mode to a simple website using javascript and the localStorage property of the window object.

The localStorage property will be used in order to maintain dark mode even after the page is refreshed.

Note: Before we start, I'd like to say that the best way to gain a lot from this tutorial is by following along, especially if you are a beginner.. (though it's not necessary, it's better if you could).

Some fun facts about localStorage

  1. localStorage is quite similar to sessionStorage; the difference is that in sessionStorage, data is cleared whenever a session ends (a tab or window is closed) while in localStorage, data is retained even after the end of a session.
  2. It stores data in key value pairs like in JSON format.
  3. localStorage for a private tab is cleared when the last private tab is closed.
  4. localStorage size is limited to 5MB per app per browser
  5. It can only store strings.

Let's begin…

  1. Create an index.html file and copy the following html code into it.
<!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</title>     <link rel="stylesheet" href="style.css" />   </head>   <body>     <div class="box">i am a box</div>     <button class="switch">toggle dark mode</button>     <script src="darkmode.js"></script>   </body> </html>  
Enter fullscreen mode Exit fullscreen mode

So for the above html code, what we did is link our html file with our style.css and darkmode.js files. We also created a box with some text and a button to enable us switch dark mode.

  1. Create a style.css file and copy the following code into it.
body {   height: 100vh;   width: 100vw;   display: flex;   justify-content: center;   align-items: center;   flex-direction: column; } .box {   height: 100px;   width: 100px;   background-color: black;   color: white;   display: flex;   justify-content: center;   align-items: center;   margin-bottom: 20px; } .darkMode {   background-color: black; } .darkMode > .box {   background-color: white;   color: black; } 
Enter fullscreen mode Exit fullscreen mode

In our style.css file:

  • We first set the height and width of our body element and centered our box div in the body using flexbox. We also change the flex-direction from row to column to make it look prettier.

  • Secondly, we set height and width of our box div, gave it a background color and centered the text inside of it using flexbox. We also added a margin bottom to it so as to create a little space between the box and the button

  • We also added some styles for our dark mode but it doesn't have any effect on the page yet, as we are going to activate it using javascript.

  1. Create the darkmode.js file and add the following code to it.
let darkMode = localStorage.getItem("darkMode");  if (darkMode == "true") {   addDarkMode(); } document.querySelector(".switch").addEventListener("click", function () {   darkMode = localStorage.getItem("darkMode");   if (darkMode == "true") {     removeDarkMode();   } else {     addDarkMode();   } });  function addDarkMode() {   darkMode = localStorage.setItem("darkMode", "true");   document.getElementsByTagName("body")[0].classList.add("darkMode"); }  function removeDarkMode() {   darkMode = localStorage.setItem("darkMode", "false");   document.getElementsByTagName("body")[0].classList.remove("darkMode"); }  
Enter fullscreen mode Exit fullscreen mode

Here's what we did in the javascript code.

  1. We first try to get the value for the dark mode using the getItem() method. The getItem() method takes a key as its argument and returns the value for that key (if it is set) or null (if it is not).
  2. The next thing we did, was to check if the value is set to true, and if it is, we call the addDarkMode() function which updates the value of the darkMode variable (the variable was declared at the top using the let keyword, so it can be updated) by setting the value of the darkMode key to true using the setItem() method. The first argument of the setItem() method is the key, while the second argument is its value. Then we add the darkMode class to the body element. So those CSS styles under the darkMode class can be added.
  3. The final thing we did, was to add a click event listener to our button after it has been queried from the DOM, we fetch the value of the darkMode from the localStorage and check if it is true, so we can call our addDarkMode() function or false so we can call our removeDarkMode() function. The removeDarkMode() function is the same with the addDarkMode() function; the only difference is that the removeDarkMode() function removes the darkMode class from the body element while the addDarkMode() function adds it.

Once you've clicked the switch button, the value for the dark mode is set and will always be remembered by the browser even when the page is refreshed or at the end of a session. This is the reason why we try to get the value of darkMode at the top of our javascript code. So that once the page reloads, or we visit our website again, It will first get the value that we have set previously and set the dark mode depending on what the value of the key may be (true or false).

beginnersjavascripttutorialwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.