Embracing either dark or light mode

Can anyone give advice on how to integrate a feature like this onto my website? I've attempted to use plugins with no success. It doesn't need to be too complex.

Does anyone have experience with this or know of a solution they could suggest? Alternatively, is there a way to implement it using JavaScript?

Answer №1

Here is a practical method that I have utilized on numerous occasions:

  • In the primary HTML document, I initially load the default theme, such as the light theme:
<link rel="stylesheet" href="/themes/light/theme.css" id="linkTheme" />
  • Subsequently, on the theme selector button/menu, I switch the CSS file referenced in the above link to load the appropriate one, like this:
const handleToggleTheme = (dark) => {
    const lightUrl = "/themes/light/theme.css";
    const darkUrl = "/themes/dark/theme.css";

    if (dark) {
      document.getElementById('linkTheme').setAttribute('href', darkUrl);
    }
    else {
      document.getElementById('linkTheme').setAttribute('href', lightUrl);
    }
  }

Answer №2

One simple solution is to create a button that toggles a boolean value. Depending on the boolean's state, you can adjust the background color of specific items to switch them to dark mode.

Answer №3

In my experience, I implemented react context for this project, utilizing a similar approach to this (I found their use of theme as an example quite insightful). I recommend delving into it further.

Answer №4

Depending on the framework you are using, there are different options available. For example, if you are using Material-UI, you can easily switch between light and dark modes to meet your needs. Check out the documentation here.

If you are not using a framework, you can create two CSS classes - one for light mode and one for dark mode. These classes can define properties such as colors and background colors. When a toggle theme button is clicked, you can switch all your elements from the light to the dark class, creating a seamless transition. You can also add animations for a more polished effect.

Answer №5

When facing this issue, there are several ways to solve it. If you are working within a specific framework, be sure to explore if there is a built-in solution available. If not, there are still multiple options at your disposal. One suggestion is to create individual CSS classes for each element that you wish to modify for dark mode. Then, utilize JavaScript to create a function that can be triggered by a button in the HTML. This function will apply the new classes to the desired elements. Clicking the button again will revert the changes back to the original CSS classes.

Answer №6

Perhaps this guide will give you a head start.

<html class="theme-light">
  <style>
    html, body {
      margin: 0;
      padding: 0;
      height: 100%;
      width: 100%;
    }

    .theme-light {
      --color-primary: #0060df;
      --color-secondary: #fbfbfe;
      --color-accent: #fd6f53;
      --font-color: #000000;
    }

    .theme-dark {
      --color-primary: #17ed90;
      --color-secondary: #243133;
      --color-accent: #12cdea;
      --font-color: #ffffff;
    }

    .container {
      display: flex;
      width: 100%;
      height: 100%;
      background: var(--color-secondary);
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }

    .container h1 {
      color: var(--font-color);
    }

    .container button {
      color: var(--font-color);
      background: var(--color-primary);
      padding: 10px 20px;
      border: 0;
      border-radius: 5px;
    }
  </style>

  <script>
    // Select a Theme
    function selectTheme(themeName) {
      localStorage.setItem('theme', themeName);
      document.documentElement.className = themeName;
    }

    // Toggle Between light and dark themes and vice versa
    function toggleTheme() {
      if (localStorage.getItem('theme') === 'theme-dark') {
        selectTheme('theme-light');
      } else {
        selectTheme('theme-dark');
      }
    }

    // Apply Theme on Page Load
    (function() {
      if (localStorage.getItem('theme') === 'theme-dark') {
        selectTheme('theme-dark');
      } else {
        selectTheme('theme-light');
      }
    })();
  </script>

  <body>
    <div class="container">
      <h1>Theme Switcher</h1>
      <button id="switch" onclick="toggleTheme()">Switch Theme</button>
    </div>
  </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

Is it possible to use jQuery for drag-and-drop functionality?

Currently, I am working on developing a drag-and-drop widget that consists of 3 questions and corresponding answers. The user should only be able to fill in 2 answers in any order, while the third drop area should be disabled. This third drop area can be l ...

Remove the attribute from the element in the ng-repeat loop

Here is my ng-repeat code snippet: <th ng-repeat="field in tableFields" translate="{{field.headerTitle | translate}}" ts-criteria="{{field.sortable ? field.fieldKey : null}}"> <label class="i-checks" ng-if="field.isCheckbox"> & ...

Vue.js computed property experiencing a minor setback

I'm currently working on developing a test-taking system using Vue and Laravel. When a user inputs the test code and email address, they are directed to the test page. To display all the test questions based on the entered code, I implemented a naviga ...

The challenge with our unique PHP/JS Analytics Solution

Here's an illustration of the code snippet for Google Analytics: <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'userIDhere']); _gaq.push(['_trackPageview']); _gaq.push([&apos ...

I am encountering a problem with the app.patch() function not working properly. Although the get and delete functions are functioning as expected, the patch function seems to be

I am in the process of setting up a server that can handle CRUD operations. The Movie model currently only consists of one property, which is the title. Although I can create new movies, delete existing ones, and even search for a ...

Erase every element contained within the div

What steps should I take to clear out the elements within my mainDiv? <div id='mainDiv'> <fieldset> <div> <input type='text'> <select></select> </div> ...

Generate a new passport session for a user who is currently logged in

I am currently utilizing passport js for handling the login registration process. After a new user logs in, a custom cookie is generated on the browser containing a unique key from the database. Here's how the program operates: When a new user logs ...

How to toggle between two background colors in a webpage with the click of a button using JavaScript

I need help with a unique website feature. I want to implement a button that cycles between two different background colors (white and black) as well as changes the font color from black to white, and vice versa. My goal is to create a negative version of ...

What is the process for crafting a Vuejs controlled input form?

Although I am familiar with creating controlled components in React using state, I am new to the Vue framework and would like to understand how to adapt my code from React to be compatible with Vue. My goal is to store the values of input fields in a data ...

Setting up Datatables using AngularJS

I am working on a controller that organizes song rankings based on sales data. Upon initialization, the controller automatically sends an HTTP GET request to retrieve all the songs needed for display (currently set at the top 20 songs). If I ever need to a ...

Can a function be passed to the URL field in an AJAX request?

Can a function be passed to the url field in an ajax call? I am looking to dynamically change the url being used in the ajax call. function generateURL(){} $.ajax({ url: generateURL, context: document.body, success: function(){ $(this).addCla ...

Uploading directly to AWS S3: SignatureDoesNotMatch error specifically for Internet Explorer users

My process involves using Amazon Web Service S3 for uploading and storing files. I create a pre-signed URL using the AWS SDK for Node.js on the server-side to enable direct file uploads from the browser through this signature URL. The Process On the serv ...

When implementing ReplaySubject in Angular for a PUT request, the issue of data loss arises

I seem to be encountering a problem with the ReplaySubject. I can't quite pinpoint what I've done wrong, but the issue is that whenever I make a change and save it in the backend, the ReplaySubject fetches new data but fails to display it on the ...

What is the best way to restrict user input to specific numbers only?

I have a text input field, how can I ensure that only numeric values from 1 to 31 are allowed? <input type="number" min="1" max="31"> ...

Which specific file name patterns does npm publish consistently exclude?

When using the npm publish command, the documentation mentions that certain files will not be included in the package unless explicitly added to the "files" list in package.json or un-ignored with a specific rule. What exactly are these "certain patterns"? ...

HTML Element Split in Two by a Line in the Middle

Greetings to all, after observing for a while I have decided to make my first post here (and just to clarify, I am an electrical engineer, not a programmer). I am in search of creating a unique element in HTML where I can detect clicks on both its upper a ...

another solution instead of using several try-catch blocks within a function

Consider a scenario where we define a function as shown below: async function doSomethingWithFriends() { let user, friends, friendsOfFriends = null; try { user = await getUser(); } catch(err){ return [401, err] } try { ...

What is the correct approach for detecting object collisions in Phaser 3?

Hey everyone, I'm facing a problem and could use some assistance. Currently, I am trying to detect when two containers collide in my project. However, the issue is that the collision is being detected before the objects even start moving on screen. It ...

The technique of using Javascript x to escape characters is

I've come across a handful of other software programs that feature a similar construct: let str = '\x32\x20\x60\x78\x6e\x7a\x9c\x89'; As I experimented with the sequence of numbers and letters within ...

Using CSS or JavaScript to trigger events while scrolling with touch

Imagine a scenario where multiple boxes are stacked on top of each other: <div style="width: 100%; height: 100px; background-color: red"> stuff </div> By clicking or touching them, the background color can be easily changed using CSS (:hover, ...