Switch from using a select tag to a check box to easily switch between a dark and light theme

I have implemented a feature on my website that allows users to toggle between dark and light themes using the select tag with jQuery.

Here is the code snippet that I am currently using:

$(function() {
  // Code for changing stylesheets based on select option
});

$(document).ready(function() {
  // Code for setting the value of the select element
});

Now, I want to replace the select tag with a checkbox for toggling between themes/stylesheets.

Update

I have updated the code snippet successfully to achieve this functionality:

 $(document).ready(function() {
        // Code for implementing theme toggle functionality using a checkbox
    });
<?php
if (isset($_COOKIE['css'])) {
    $style = $_COOKIE['css'];
} else {
    $style = 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min';
}
?>

  <!DOCTYPE html>
  <html>

  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Dashboard</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="<?php echo $style; ?>.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js"></script>
  </head>

  <body>
    <div class="style">
      <label>Dark Theme</label>
      <input type="checkbox" name="" id="style">
      <button type="submit" id="btnSubmit" class="btn btn-success">Change</button>
    </div>
  </body>

  </html>

Answer №1

One possible approach is to insert a specific attribute into the checkbox element

<input id="#checkbox" type="checkbox" data-value="selected">

Next, you can implement the following logic:

if($("#checkbox").data("value") === "selected"){
   activateDarkMode();
}else{
   activateLightMode();

Answer №2

There is just one error that needs to be corrected - $('#btnSumbit') should actually be $('#btnSubmit').

$(document).ready(function() {


    $('#style').click(function() {

        var style = this.checked ? 'https://bootswatch.com/3/darkly/bootstrap.min' : 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min';

        $('body').fadeOut("slow", function() {
            $('link[rel="stylesheet"]').attr("href", style + ".css");
            $('body').fadeIn("slow");

        });

    });
    
    var defaulttheme = 'https://bootswatch.com/3/darkly/bootstrap.min';
if(defaulttheme == 'https://bootswatch.com/3/darkly/bootstrap.min'){
$('#style').attr("checked",true); //do when you just want to update checked status
$('#style').click();
//do when you want to set initial theme to dark


}
});
<?php
if (isset($_COOKIE['css'])) {
    $style = $_COOKIE['css'];
} else {
    $style = 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min';
}
?>

  <!DOCTYPE html>
  <html>

  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Dashboard</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="<?php echo $style; ?>.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js"></script>
  </head>

  <body>
    <div class="style">
      <label>Dark Theme</label>
      <input type="checkbox" name="" id="style">
      <button type="submit" id="btnSubmit" class="btn btn-success">Change</button>
    </div>
  </body>

  </html>

Answer №3

I am looking to implement a checkbox for switching between different themes or stylesheets on my website

Achieving this functionality is indeed possible:

$(function() {
  $('#dark').on('change', function() {
    var href = 'https://www.w3schools.com/lib/w3-theme-indigo.css';
    if (this.checked) {
      href = 'https://www.w3schools.com/lib/w3-theme-black.css';
    }
    $('<link>', {
      'href': href,
      'rel': 'stylesheet'
    }).appendTo('body');
  }).trigger('change');
});
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label id='lbl'><input id='dark' type="checkbox"/>Use Dark Theme</label>

<div class="w3-card-4">
  <div class="w3-container w3-theme w3-card">
    <h1>Indigo</h1>
  </div>

  <div class="w3-container w3-text-theme">
    <h2>w3-text-theme</h2>
  </div>
</div>

For further details, you can visit the website here

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

Having trouble connecting to my MongoDB container using Node.js

I am facing an issue while trying to connect my local mongoDB docker, named "some-mongo", to my NodeJS backend server running on the same computer. The problem arises when attempting to establish the connection using the "mongoose" module. To launch my mo ...

Creating an array like this in JavaScript during an API call using Ajax

"WorkingHours": { "Monday" : { "open" : "10:00 am", "close" :"5:00 pm" }, "Wednesday" : { "open" : "10:00 am", "close" :"5:00 pm" ...

Adjusting the size of text in KineticJS to ensure it fits comfortably within a rectangle while

Check out this link: http://jsfiddle.net/6VRxE/11/ Looking for a way to dynamically adjust text, text size, and padding to fit inside a rectangle and be vertically aligned? Here's the code snippet: var messageText = new Kinetic.Text({ x: .25* ...

Adjust the color of an SVG icon depending on its 'liked' status

In my React/TypeScript app, I have implemented an Upvote component that allows users to upvote a post or remove their upvote. The icon used for the upvote is sourced from the Grommet-Icons section of the react-icons package. When a user clicks on the icon ...

Struggling to Achieve Consistent Design Across Different Browsers When Styling a Calendar

My webpage has a calendar that retrieves data from the server using Jquery. Interestingly, the calendar looks perfect on Google Chrome but falls apart on Firefox. I can't seem to style it to make it look consistent across different browsers like in C ...

A guide to storing a JavaScript variable in a MySQL database using Express.js

Looking for some guidance on node js and expressjs framework. While developing a web application, I've encountered an issue with saving data into the database. Everything seems to be set up correctly, but the data stored in the variable (MyID) is not ...

Issue with the footer not remaining at the bottom of the page

I'm in the process of updating my website and have come across an issue with the footer placement on one specific page. Typically, the footer stays at the bottom of all pages except for this particular page where it appears floated to the left instead ...

"How to Use jQuery to Target a <span> Element by

hello there sometimes you just lose track and can't even remember how to search for something that you've lost <div> <table cellspacing="0" rules="all" border="1" id="ctl00_DefaultContent_migrationGridView" style="height:90%;wi ...

Looping through mysql data horizontally within a div tag

Looking for assistance to create a content loop similar to the one on this website? I attempted to use a while() loop, but it ended up displaying vertically without using a table. I suspect this page utilizes thumbnails. What I aim for is to have the it ...

Transforming a numerical function into an HTML span tag: A quick guide

Looking for assistance with updating the last line. The goal is to display the current month, obtained from the getMonthText variable, within the <h1><span id="month_year">&nbsp;</span></h1> Starting code. The issue arises to ...

Tips for keeping a div visible while hovering over a link using only CSS

Apologies for any language errors in advance. I will do my best to explain my issue accurately: In my CSS, I have created a hidden div that is displayed none by default. When I hover over a link in the navigation bar, I change the display to block, creati ...

The amazing feature known as "CSS3 background-clip"

Seeking a solution for restricting a background image to the text within an h2 element using -webkit-background-clip. Wondering if -moz-background-clip functions in the same way as -webkit-background-clip. As it currently only works in webkit browsers, it ...

Troubleshooting Issues with Loading Styles and JavaScript for Wordpress Plugin in Admin Area

Can someone please help me with troubleshooting my stylesheet and scripts that are not working properly? I have included styles in the stylesheet and an alert in my script file, but for some reason they are not functioning as expected. (I have confirmed ...

Issue with Jquery firing function during onunload event

I'm having trouble adding a listener to a form in order to trigger an ajax call when the user leaves it. I can't seem to identify any errors in Firefox and nothing is getting logged in the console, indicating that my code might be incorrect. As s ...

Cross-building targets for Node modules for deployment on npm platform

I'm working on an ES6 module that needs to be compatible with different environments. I'm not sure whether to use webpack or rollup for building, and how to target specific environments. Building for Different Environments ES6 environments like ...

Utilizing Jade template helpers in both Node.js and the browser

When working with Jade templates in both an Express app and a browser environment, I find myself needing to format data before inserting it into inputs. Is it recommended to extend locals with similar functions in both Node.js and the browser? { formatDa ...

Adding a CSS link to the header using JavaScript/jQuery

Is there a way to dynamically inject a CSS link located in the middle of an HTML page into the head using JavaScript? <head> ... styles here </head> <body> code <link href='http://fonts.googleapis.com/css?family=Lato:400,300, ...

What is the best way to choose a specific JSON element?

Seeking information from an API, my goal is to extract specific data using JavaScript selectors. I am specifically interested in two objects from the JSON below: [ { "symbol": { "tickerSymbol": "@CH20", "vendor": "DTN", "marketName ...

Issue with retrieving the positions of two numbers in an array

I encountered a challenge: I have an array of integers nums and an integer target. My goal is to find the indices of two numbers in the array that add up to the specified target. Example 1: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Output: Thi ...

having trouble capturing the web element containing _ngcontent-c6 using python and selenium

I am having trouble capturing the highlighted web element in the screenshot below: https://i.sstatic.net/7ihmD.png I have attempted various options using both absolute and relative paths: submit = driver.find_element_by_xpath("html/body/vra-root/vr ...