A step-by-step guide on toggling between light mode and dark mode using water.css

Implementing the water.css on my website, I have this JavaScript code:

function setTheme(themeName) {
    localStorage.setItem('theme', themeName);
    document.documentElement.className = themeName;
}
// function to toggle between light and dark theme
function toggleTheme() {
    if (localStorage.getItem('theme') === 'theme-dark') {
        setTheme('theme-light');
    } else {
        setTheme('theme-dark');
    }
}
// Immediately invoked function to set the theme on initial load
(function () {
   if (localStorage.getItem('theme') === 'theme-dark') {
      setTheme('theme-dark');
   } else {
      setTheme('theme-light');
   }
})();

Along with a button to switch themes:

<div class="container">
        <h1>Theme Switcher</h1>
        <button id="switch" onclick="toggleTheme()">Switch</button>
    </div>

I have included the JavaScript file and now wish to modify the code to switch between 2 CDN links: dark.min.css

<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/kognise/water.css@latest/dist/dark.min.css">

and light.min.css

<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/kognise/water.css@latest/dist/light.min.css">

Answer №1

Learn how to switch themes easily:

html

<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <title>Document</title>
  </head>

  <body>
    <div class="container">
      <h1>Theme Switcher</h1>
      <button id="switch" onclick="toggleTheme()">Switch</button>
    </div>
  </body>

</html>

javascript

function updateTheme(themeName) {
  localStorage.setItem('theme', themeName);

  var link = document.createElement('link');
  link.rel = 'stylesheet';
  if (themeName == "dark-theme") {
    link.href = 'https://cdn.jsdelivr.net/gh/kognise/water.css@latest/dist/dark.min.css';
  } else {
    link.href = 'https://cdn.jsdelivr.net/gh/kognise/water.css@latest/dist/light.min.css';
  }
  document.head.appendChild(link);
}

function toggleTheme() {
  if (localStorage.getItem('theme') === 'dark-theme') {
    updateTheme('light-theme');
  } else {
    updateTheme('dark-theme');
  }
}

(function() {
  if (localStorage.getItem('theme') === 'dark-theme') {
    updateTheme('dark-theme');
  } else {
    updateTheme('light-theme');
  }
})();

The key changes were made in the updateTheme function:

var link = document.createElement('link');
  link.rel = 'stylesheet';
  if (themeName == "dark-theme") {
    link.href = 'https://cdn.jsdelivr.net/gh/kognise/water.css@latest/dist/dark.min.css';
  } else {
    link.href = 'https://cdn.jsdelivr.net/gh/kognise/water.css@latest/dist/light.min.css';
  }
  document.head.appendChild(link);

This will apply the appropriate css based on your chosen theme.

Check out this JSFiddle for a live demo.

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

How can I delete the header and footer on a personalized homepage design?

After crafting a unique home page/landing page for my website that stands out from the rest, I've come across an issue. The header and footer are appearing on this new page, but I only want to display what I specifically coded. I attempted using Site ...

What is the best way to position the publication date of an article at the bottom of the

I am looking to have the article publishing date (1/9/2016) positioned at the bottom inside the container. Right now, the date appears just below the text, but I want it to be aligned at the bottom of the container. The website in question is watchathletic ...

Table lines that are indented

I am currently in the process of transforming a standard HTML table into an indented version like this: Is there a way to hide the initial part of the border so that it aligns with the start of the text, even if I can't do it directly in HTML? ...

Utilizing jQuery to Maintain State Across Page Refreshes with Cookies

Currently, I am attempting to create a script that can retain its state even after the page is refreshed. Here is my progress so far: Utilizing jQuery: $(window).ready(function() { var voteId = $('.gallery-item a'); $(voteId).click(function() ...

Is it possible to simultaneously run two Node.js projects on Windows?

Is it possible to run two Node.js projects on a Windows operating system? If so, what is the process for doing that? If not, can I run two Node.js projects on a dedicated host instead? ...

Is there a way to make the <iframe> adjust its size as the element it contains grows, without

Seeking assistance with a specific issue. My goal is to have an iframe appear on hover of another element and expand with it. The problem I'm facing is that the iframe shows up quickly and extends beyond its parent container. Here's what I have: ...

Adding descriptive text before a website link is a helpful way to provide context for the reader. For example

My goal is not just to have JavaScript change the URL after my page has loaded. I want to be able to enter something like 'blog.mywebsite.com' into the omnibar and have it locate my website similar to how Steam does with 'store.steampowered. ...

What is the purpose of employing useMemo in the Material-UI autocomplete documentation?

My focus is on this specific demo in the autocomplete documentation. In the google maps example, there is a throttled function that is returned from a useMemo with an empty array as the second parameter. However, it raises the question of what exactly is ...

Linking Java objects with Node.js variables

In this snippet of code, I am utilizing the 'java' module in node.js to create Java objects. Specifically, I am creating four Java objects and aiming to consolidate them as a single object by using the variable 'args' to store these Jav ...

Tips for validating email addresses and enforcing minimum length requirements

In order to validate email input for the correct format and ensure minimum length validations for first name and password, I am looking to utilize only bootstrap. While I have successfully implemented required field validations for the inputs, I am unsure ...

Angular's input event fails to trigger for dynamically generated fields when pasted into them

When working with a form that has dynamically generated input fields, I encountered an issue. I needed to display a preview of the input contents on a div while pasting content into the fields. This project is built using Angular 11. Below is my .ts file: ...

Having trouble with the scrollbar appearance after updating Chrome?

I've encountered an issue with my code after the latest Chrome update. Is there a way to implement cross-browser styling for scrollbars? // Looking for Scrollbar Styling Solution const scrollbarStyle = { scrollbarColor: `${themeLayers.scrollBar[0 ...

Enlarging and cutting video footage

I have developed an app that features a code enabling users to capture photos using their computer-connected camera. How it Works: A webcam is utilized to display a video element with the camera as its source: function onSuccess (stream) { this.video.s ...

What are the steps to modify the placeholder of the formik <Field/> component?

Struggling to figure out how to make the date input empty with Formik. I just want it to display nothing initially, but have been unable to do so after hours of trying different methods. <Field name="date" type="date" className ...

How to set the element in the render method in Backbone?

Currently, I am in the process of developing a web page utilizing BackboneJS. The structure of the HTML page consists of two divs acting as columns where each item is supposed to be displayed in either the first or second column. However, I am facing an is ...

Sending a multitude of variables using strings, evaluating them through various functions, and incorporating a variety of methods

To put it simply, my goal is to utilize an object literal that allows me to pass an unknown quantity of variables in any order to a function. While this may seem straightforward in principle, within my code, this object literal is passed to a second functi ...

I'm wondering why myDivId.toggle() is functioning properly but myDivClass.toggle() is not working as expected

Using JQuery's toggle() function, I have been able to hide and show some DIVs successfully. Recently, I discovered relationships between certain DIVs that allowed me to group them into a class. I decided to try toggling the entire class rather than ...

How to use Javascript to set focus on a dropdown list within a PHP script

Having trouble setting focus on the dropdown list in my PHP page dc-test.php, where there are two dropdown lists that are interdependent. The values for these dropdown lists are fetched from a database table. I am unable to set focus on the first dropdown ...

Decipher encoded parameters utilizing the JavaScript encodeURIComponent method

I'm dealing with an issue in my application where text entered by a user is sent to the server as part of a URL to render an image. The text is encoded using the encodeURIComponent function, but I'm running into problems with certain characters l ...

Is there a way to set the background of the first sibling element to blue, but change it when another sibling element is hovered over?

I have a list of names: <div>Timothy Gruns</div> <div>Lawrence Fishly</div> <div>Jackson Crolya</div> What I want is for the background color to change to blue when any name is hovered over. However, if no names are be ...