How to create simple Dark/Light mode for web using JavaScript

Light-on-dark color scheme, also called dark mode, is a supplemental mode that uses a color scheme in which content of a webpage is displayed on a dark background. Such a color scheme reduces the light emitted by screens and enhances readability. Switching to dark mode allows website users to move to an eye-friendly and resource-saving design whenever they want. 



 

 

 

 

 

 

Step 1: Create an HTML Document

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Dark/Light Mode</title>
     
    <script src=
"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js">
    </script>
</head>
 
<body>
    <div class="mode">
      <img src="https://cdn.iconscout.com/icon/free/png-256/night-mode-2-475098.png" id="icon">
    </div>
     
    <div class="content">
        <h1>Mcharrtyq</h1>
        <p><i>Best Selling for Windows services</i></p>
        <h3>Light and Dark Mode</h3>
        <p>
            Click on the switch on top-right
        </p>
    </div>
</body>
</html>

 

 

 

 

 

 

Step 2: add a Style 

@import url('https://fonts.googleapis.com/css2?family=Fredoka:wght@400;500;600;700&display=swap');
*{
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
:root {
    --darkblue: #ffffff;
    --white: #291D5A;
    --black: #ffffff;
    --darkpuple: #F3F3F3;
    --dark-gray: #ADADAD;
    --gray: #ededed;
    --lightgray: #000000;
}
.dark-mode{
    --darkblue: #291D5A;
    --white: #ffffff;
    --black: #000000;
    --darkpuple: #463589;
    --lightgray: #F3F3F3;
}
body{
    background: var(--darkblue);
    font-family: 'Fredoka', sans-serif;
    display: flex;
    flex-direction: column;
    margin: auto;
    justify-content: center;
    align-items: center;
}

#icon{
    color: black;
    width: 30px;
    height: 30px;
  margin-top: 9.5rem;
  margin-left: 8rem;
  cursor: pointer;
}
.content{
  text-align: center;
  margin: 0 2rem;
}
.content h1, h3{
  color: var(--white);
  margin: 0.5rem 0;
}
.content p{
  color: var(--lightgray);
}

Last Step: add Javascript code

const darkIcon = document.getElementById('icon');
darkIcon.addEventListener('click', () => {
  const lightIcon = document.getElementById('icon');
  document.body.classList.toggle('dark-mode');
  if (document.body.classList.contains('dark-mode')) {
    icon.src = 'https://cdn4.iconfinder.com/data/icons/multimedia-flat-30px/30/sun_light_mode_day-512.png';

   
} else {   

    icon.src = 'https://cdn.iconscout.com/icon/free/png-256/night-mode-2-475098.png';

  }
})

 

 

 

 

 

 

 

 

 

Output: 


    

    Support Me with
    gmail: elvinafirmansyah@gmail.com

 

 

 

 

 

 

 

 



Komentar

Posting Komentar