Opt for buttons for color selection instead of a checkbox toggle

I attempted different approaches to replace the existing checkbox with a button but encountered difficulty. Using the onClick method also proved unsuccessful.

VIEW DEMO HERE: https://jsfiddle.net/yxez4a2u/

HTML:

<div class="form-check form-switch">
  <input class="form-check-input" type="checkbox" id="darkModeSwitch" checked>
  <label class="form-check-label" for="darkModeSwitch">Dark Mode</label>
</div>

<button type="button" onclick="darkModeSwitch('light')"> Light </button>
<button type="button" onclick="darkModeSwitch('dark')"> Dark </button>

<p>
This showcases Bootstrap 5 color mode functionality with storage capabilities.
</p>

JS:

document.addEventListener('DOMContentLoaded', (event) => {
    const htmlElement = document.documentElement;
    const switchElement = document.getElementById('darkModeSwitch');

    // Set default theme to dark if no setting is found in local storage
    const currentTheme = localStorage.getItem('bsTheme') || 'light';
    htmlElement.setAttribute('data-bs-theme', currentTheme);
    switchElement.checked = currentTheme === 'light';

    switchElement.addEventListener('change', function () {
        if (this.checked) {
            htmlElement.setAttribute('data-bs-theme', 'light');
            localStorage.setItem('bsTheme', 'light');
        } else {
            htmlElement.setAttribute('data-bs-theme', 'dark');
            localStorage.setItem('bsTheme', 'dark');
        }
    });
});

Answer №1

By assigning IDs to the button elements, you are able to target and select them. Then, with an event listener added to each button, they are given a click function that triggers the setTheme function with different arguments. This function then stores the chosen theme in the localStorage.

<div class="form-check form-switch">
  <input class="form-check-input" type="checkbox" id="darkModeSwitch" checked>
  <label class="form-check-label" for="darkModeSwitch">Dark Mode</label>
</div>

<button type="button" id="lightModeButton"> Light </button>
<button type="button" id="darkModeButton"> Dark </button>

<p>
This page demonstrates Bootstrap 5 color mode with storage functionality.
</p>

document.addEventListener('DOMContentLoaded', (event) => {
const htmlElement = document.documentElement;
const switchElement = document.getElementById('darkModeSwitch');
const lightModeButton = document.getElementById('lightModeButton');
const darkModeButton = document.getElementById('darkModeButton');

const currentTheme = localStorage.getItem('bsTheme') || 'light';
htmlElement.setAttribute('data-bs-theme', currentTheme);
switchElement.checked = currentTheme === 'light';

function setTheme(theme) {
    htmlElement.setAttribute('data-bs-theme', theme);
    localStorage.setItem('bsTheme', theme);
    switchElement.checked = theme === 'light';
}

switchElement.addEventListener('change', function () {
    setTheme(this.checked ? 'light' : 'dark');
});

lightModeButton.addEventListener('click', function () {
    setTheme('light');
});

darkModeButton.addEventListener('click', function () {
    setTheme('dark');
});
});

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

Redirecting to the homepage with ScrollTop feature

With the development of my Single page HTML5 web application, I have encountered a scrolling issue. To scroll to the top of the page, I am implementing the following code: $('html, body').animate({ scrollTop: 0 }, 800); This functionality works ...

Ways to remove any messages containing URLs that are not www.youtube.com or www.twitter.com

Recently, I have encountered a significant issue with Discord Scam Links in my server. I attempted the following approach: if(message.content.includes("discordscam.com")) { message.delete() } However, this method is not effective as it onl ...

What are some ways to implement querySelectorAll in conjunction with htmx?

I'm currently using htmx, an amazing library with a small issue that I'm struggling to resolve. htmx utilizes querySelector to find elements for swapping or updating, for example with hx-swap="...", hx-target="...". How can I use querySelectorAll ...

Error: Brackets missing in the argument list

app.get("/editMBTI", editMBTIFunc(req, res) { // ensuring MongoClient is accessible in all EJS Files // app.locals.MongoClient= MongoClient; MongoClient.connect(url, function (err, client) { assert.equal(null, err); console.log( ...

Ways to retrieve JSON data using Angular JS

I'm currently working on populating my table with data. The URL returns JSON data, but I'm struggling with how to retrieve it using AngularJS. Here is my services.js: angular.module('OrganisatieApp.services', []) .factory('organi ...

Encountered an Xpath error while attempting to create a random email generator using Selenium IDE

While attempting to execute a script, I encountered an "element not found" error with Selenium failing to detect the xpath. My goal is to randomly generate email addresses. Every time there is an error message stating: [error] Element .//[@id='GmailA ...

Issue with Chrome extension's popup not displaying

I was developing a chrome extension, but I encountered an issue where the popup does not display when clicking on the icon. After researching online, I found suggestions to change page_action to browser_action. However, even after making this adjustment, ...

Issue with JQuery Ajax call within If condition

My Ajax call is working perfectly in one scenario, but not in another when placed inside an if statement. I'm relatively new to JS and Ajax, so I may be missing something fundamental. Any insights would be appreciated. Thank you. The function that wo ...

Vue: Ensuring one method finishes executing before triggering the next one

I've implemented two methods in my Vue instance; const app = new Vue({ el: '#app', data: { id: null }, methods: { getId: function() { return axios.get('url') .then(response => response.data) .then(i ...

Incomplete data was retrieved from the localStorage

I am currently in the process of developing a mobile application using Phonegap version 1.4.1. I have encountered an issue on iOS (running on version 5.1) where the app fails to load all data from localStorage. Upon first use of the app, I set a flag in l ...

The MUI Module is missing: Unable to locate '@emotion/react'

Attempted this solution, but unfortunately it did not work Currently using the latest version of Material-UI Error: Module not found: Can't resolve '@emotion/react' Let's try installing it then.. npm i @emotion/react @emotion/style ...

The appearance of all input forms in MaterializeCSS when used in an electron environment appears to

After following the instructions here on how to get started with Materialize CSS, I am having issues with my input form appearing strange: https://i.sstatic.net/lveS2.png The contents of my current index.html file are as follows: <!DOCTYPE html> &l ...

Using Jquery and Ajax to add information to a database

One of the challenges I'm facing involves a page with three forms, each containing separate variables that need to be inserted into a MySQL database for viewing. My current script is working fine, even though I am aware that `mySql_` is deprecated but ...

What is the best way to retrieve the present value of an input that belongs to an array of objects?

Struggling with populating an array with data and encountering a specific issue. 1 - Attempting to determine an index for each key in the array of objects, but encountering an error when a new input is added dynamically. The inputs are successfully added ...

Managing extensive amounts of data with server-side scripting in a Datatable

I am exploring the use of the datatable plugin to effectively manage a large amount of data. Currently, I am interested in implementing "server side processing in datatables" with the help of server-side scripting. Since I have limited experience with AJA ...

Enhance User Experience with a Responsive Website Dropdown Menu

Currently, I am focused on enhancing the responsiveness of my website and I realized that having a well-designed menu for mobile view is essential. To address this need, I added a button that only appears when the screen size is 480px or lower, which seems ...

Closing a bootstrap alert will also close the modal it is contained within

I'm currently facing an issue with my code that involves displaying an alert on top of a modal. The problem arises when I try to dismiss the alert using the 'x' button - it ends up dismissing the entire modal as well. Although I've foll ...

How come when I click on the edit button, the selected data's model doesn't appear in the dropdown menu as I would like it to?

this is the function in my controller public function getModel($make_id = null) { $make_id = request()->make_id; $carsmodel = CarModel::where('make_id', $make_id)->orderBy('model', 'ASC')->get(); return re ...

Is it possible to customize the MongoDB Collection before loading the web application by fetching data asynchronously using Promises?

I am currently working with MongoDB and NodeJS, trying to preload my Collection customers every time the site is loaded. The process involves emptying the collection, populating it with empty Documents, and then replacing them with real data fetched from a ...

Enhancing the efficiency of nested ajax calls loop

Disclaimer: While the final result is successful, I am struggling to comprehend the sequence in which a loop of nested ajax calls operates. Essentially, I have two ajax calls that fetch data from an external API using curl GET requests. They both rely on ...