Guide to making a toggle button with a Light/Dark mode functionality

I have implemented a light/dark toggle button and now I want to integrate the functionality for switching between light and dark themes on my webpage. The switch should toggle the theme between dark and light modes when clicked. Some basic styling has been applied to the switch to display either the light or dark theme upon toggling.

<html>
  <div class="theme-toggle" style="cursor: pointer;">
    <input type="checkbox" checked style="cursor: pointer;">
    <div class="toggle-body" style="cursor: pointer;"></div>
    <div class="celestial-body" style="cursor: pointer;"></div>
  </div>
  <style>
     :root {
      --width: 60px;
      --height: 30px;
    }
    
    body {
      font-family: monaco, sans-serif;
      box-sizing: border-box;
      margin: 0;
      padding: 0;
      margin: 2em;
    }
    
    .theme-toggle {
      position: relative;
      width: var(--width);
      height: var(--height);
    }
    
    .theme-toggle input[type="checkbox"] {
      position: absolute;
      top: 0;
      left: 0;
      opacity: 0;
      z-index: 1;
      width: var(--width);
      height: var(--height);
    }
    
    .theme-toggle .toggle-body {
      position: absolute;
      top: 0;
      left: 0;
      width: var(--width);
      height: var(--height);
      border: 2px solid #080808;
      border-radius: var(--height);
      transition: all 80ms ease-in-out;
    }
    
    .theme-toggle input[type="checkbox"]~.toggle-body {
      background: #1d1d1d;
      background-image: url("https://cdn.glitch.com/9be3ef5e-cf68-4fac-9bd5-82714468aed6%2F1e7b6b11b5b398711c60f2b71cdf9b03.gif?v=1599237363310");
      background-size: cover;
    }

...

</html>

You can access this code snippet on JSFiddle. I have incorporated a light/dark mode feature for my website where the theme changes to light or dark mode upon clicking with the help of the onclick() function.

Answer №1

To easily switch between modes, consider utilizing the :root color scheme.

By simply clicking a button, you can trigger the change in colors specified under :root.

For more details, refer to this resource: View Document

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

Count Scroller - Finding a Solution for _.debounce

Issue with Counter I have a counter that should increase or decrease by one each time the user scrolls up or down. The problem I'm facing is that my counter $('html').on('mousewheel', function (e) { var delta = e.originalEve ...

JavaScript News Scroller for Horizontal Display

After searching through numerous websites, I have yet to find the ideal horizontal news scroller for my website. My specific requirements include: Must provide a smooth scrolling experience Scroll from right to left covering 100% width of the browser ...

Limiting the click event to the parent div only

I've encountered a problem with my overlay setup. I have an overlay with a child div inside, and I want the overlay to close only when the user clicks on the overlay itself, not the child div. Even though I've implemented the closing function, it ...

The renderValue property is malfunctioning in the Material-UI native Select component

Whenever I utilize the native prop in the MUI Select component, the renderValue prop fails to function properly. Additionally, if I attempt to assign a custom value to the value prop, it does not display. Take a look at the code snippet below: const [selec ...

Are the props.children handled differently within the <Route> component compared to other React components?

Each and every react component undergoes a process in the following function, which is located in ReactElement.js within node_modules: ReactElement.createElement = function (type, config, children){ . . . } This function also encompasses <Rou ...

Leverage the power of puppeteer alongside webpack

Struggling to make puppeteer work with webpack? Despite adding it to package.json and configuring webpack.dev, the 'launch' function still throws errors. Here's what I've tried: Installed dependency in package.json: npm i puppeteer In ...

An unexpected issue occurred during runtime, specifically a TypeError stating that the function posts.map is not

Currently, I am diving into the world of nextjs and decided to follow a tutorial on building a Reddit clone that I stumbled upon on Youtube. However, I encountered a persistent issue: posts.map is not a function I would appreciate any assistance you can o ...

jQuery ajaxSetup: handling error retries for ajax calls is not possible

When using $.ajaxSetup(), I am faced with the challenge of making an AJAX request after refreshing a valid token in case the previous token has expired. The issue arises when attempting to execute $.ajax(this) within the error callback. $.ajax({ url: ...

Encountering a syntax error with JSON.parse() when using MVC 4 Razor with Jquery Ajax

I am encountering an issue with my MVC 4 application login page. I am attempting to utilize a jQuery ajax request to my login controller to check if the user exists. Here is the snippet of my jQuery code: $(document).ready(function () { $("#btnSub ...

Submitting data and files simultaneously to Ajax using Laravel

As I work on enhancing my registration page with Bootstrap Modal, I need to allow users to upload their image along with other information. HTML <form method="POST"> <center> <img name="user_image" id="proPic" src="ima ...

JavaScript malfunctioning on Chrome

Displayed on the page is a table that lists user details. When the Edit Button is clicked, it allows for the row to be edited. The code provided below works in IE but does not show any response in Chrome. I am looking to make the site compatible with bot ...

Is it possible for me to move props object deconstruction into a separate module?

Here is my scenario: I have two React components that share 90% of the same props data, but display different HTML structures. I would like to avoid duplicating variable declarations in both component files. Is there a way to extract the common props des ...

What is the best way to substitute unpredictable dynamic variables on-the-fly?

I am working with a .js file that contains a config structure similar to this: genGetLocations:{ data_url:'restaurants/{var1}/tables/{var2}, } This is just one example. Some configurations may have data_url with more than two dynamic variables. I ...

Does Peerjs exclusively cater to one-on-one webrtc communication?

Can PeerJS be used to implement one-to-many audio communication with WebRTC? I'm currently using Socket.io with Node.js. Is this sufficient for WebRTC integration? As a beginner in WebRTC, could you recommend some options for implementin ...

Breaking down JavaScript arrays into smaller parts can be referred to

Our dataset consists of around 40,000 entries that failed to synchronize with an external system. The external system requires the data to be in the form of subarrays sorted by ID and created date ascending, taken from the main array itself. Each ID can ha ...

Effortlessly transfer files with Ajax through Box

I attempted to utilize the Box.com API for file uploads according to instructions from https://gist.github.com/seanrose/5570650. However, I encountered the following error message: `XMLHttpRequest cannot load "". No 'Access-Control-Allow-Origin&ap ...

Troubleshooting CSS navigation bar hamburger dilemma

Currently, I am facing an issue with a toggle button on my website. When I click on the hamburger menu, the navigation bar does not show up even though the toggle feature is working perfectly fine. I have tried combining different sources to solve this pro ...

Discover the steps to modify the input field type with just a keypress in angularjs

I need help changing an input field type from text to password. Currently, I am able to change the input field type from text to password when clicking on it. However, I also want the type to change from text to password when tab is pressed. Any assistan ...

Struggling with implementing a personalized zoom feature in React-Leaflet?

Looking to create a custom Zoom button using react-leaflet Below is the code I have been working on: import React from 'react'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import { Map, TileLayer } from 're ...

Personalize Material design slider Label - final element

When using Material-ui, the default position of Slider's labels is centered: However, I require the labels to have a space-between position. For example: To achieve this, I tried using the '&:last-child' property for the markLabel clas ...