Changing styles with the use of bootstrap.css themes on the fly

I'm experimenting with toggling between a custom dark and light theme in my MVC application.

On the _Layout.cshtml page, the default theme is loaded by the following code:

<link id="theme" rel="stylesheet" href="~/lib/bootstrap/dist/css/Original.css ">

To switch between themes, I have created these buttons:

<button id="light">Light</button><br />
<button id="dark">Dark</button>

The two additional bootstrap themes are stored in lib > bootstrap> dist > css

In my bootstrap.js file, I've included the following JavaScript:

$('#dark').click(function () {
    $('link[href="~/lib/bootstrap/dist/css/Dark.css"]').attr('href', '~/lib/bootstrap/dist/css/Dark.css');
});
$('#light').click(function () {
    $('link[href="~/lib/bootstrap/dist/css/Dark.css"]').attr('href', '~/lib/bootstrap/dist/css/Light.css');
});

If I've overlooked an obvious mistake, I would appreciate any guidance on this matter.

Answer №1

Here is a VanillaJS solution for changing themes. Make sure to verify that the href attribute in the link tag points to the correct CSS file.

const darkModeBtn = document.querySelector('#dark');
const lightModeBtn = document.querySelector('#light');
const themeLinkTag = document.querySelector('#theme');

darkModeBtn.addEventListener('click', () => {
  themeLinkTag.setAttribute('href', '~/lib/bootstrap/dist/css/Dark.css')
});

lightModeBtn.addEventListener('click', () => {
  themeLinkTag.setAttribute('href', '~/lib/bootstrap/dist/css/Light.css')
});

Answer №2

One possible solution could be:

$('#dark').click(function () {
    $('#theme').attr('href', '~/lib/bootstrap/dist/css/Dark.css');
});
$('#light').click(function () {
    $('#theme').attr('href', '~/lib/bootstrap/dist/css/Light.css');
});

The issue lies in the href attribute of the link-element, which ASP.NET modifies to match the content-root path instead of starting with ~/. This discrepancy causes the browser to not recognize the correct file location.

https://i.sstatic.net/UbY6Z.png

Answer №3

After implementing Pieterjan's solution and including event.preventDefault(), the functionality started working as expected:

$(document).ready(function () {
            $('#dark').click(function () {
                event.preventDefault();
                $('#dynamicCss').attr('href', '/css/site-dark.css');
            });
            $('#light').click(function () {
                event.preventDefault();
                $('#dynamicCss').attr('href', '/css/site-light.css');
            });
        });

However, upon refreshing the page, the website reverts back to displaying the light theme.

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

Implementing a delay in a CSS menu design while still ensuring compatibility with browsers that do not support JavaScript

I currently have a three-tiered menu that relies on :hover and is controlled by css alone. I am now looking to introduce a slight delay to the hovers, which means transitioning my css :hovers to a .hover class and incorporating jQuery. My concern is whet ...

Tips for incorporating an unordered list inside a list item

<li class="cate-item"> <button class="cate-label" >item 1 </button> <ul class="sub-categ"> <li> sub item 1</li> <li> sub item 2</li> <li> sub item 3</li ...

Using React to pass a value through state when handling changes

Trying to implement handleChange and handleSubmit methods for a login page in React. Set username and password values in state, update them when form inputs change, then submit using the updated values. However, values print as undefined in the console. N ...

Modifying the class of multiple images within an array

I am excited to share my first post here and express my gratitude for all the solutions I have found on this platform. I encountered an issue with using .removeClass and .addClass in my recent program. I am loading multiple pictures into an array called F ...

Tips for handling value updates when a user clicks a checkbox using jQuery

Having trouble with updating values when a checkbox is clicked. When the checkbox is clicked once, the value is added correctly. However, if the user rapidly clicks on the same checkbox multiple times, the value is not added or subtracted properly and gets ...

Utilizing Selenium to scrape various URLs for similar content using subtly different XPaths

Utilizing Selenium to retrieve data from various URLs, each containing similar tables but with slightly different XPaths. See below for my code snippet: my_urls = ["https://www.sec.gov/cgi-bin/own-disp?action=getowner&CIK=0001548760", "https://www.sec.gov ...

Disregarding 'zIndex' directive within JavaScript function, an image stands apart

There is an issue with the z-index values of rows of images on my webpage. Normally, the z-index values increase as you scroll further down the page. However, I want certain items to have a lower z-index than the rest (except on hover). These items are i ...

What is causing the Bootstrap 5 navbar to not collapse?

Struggling to compile Bootstrap 5 with sass, I have a feeling that I might be missing some important scss files. When I added the <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7 ...

Absence of property persists despite the use of null coalescing and optional chaining

Having some trouble with a piece of code that utilizes optional chaining and null coalescing. Despite this, I am confused as to why it is still flagging an error about the property not existing. See image below for more details: The error message display ...

Tips on adding CSS to a React component

I've successfully converted an HTML file into a component designed to resemble a 7-segment LED display. I have imported the necessary CSS styles from the index.css file, but I am unsure how to properly apply these styles within the component. My atte ...

Text displaying as actionable icons

In my React project, I am utilizing material-table (https://material-table.com/#/) and have successfully imported the necessary icons. However, when viewing the action bar, the icons are displaying as plain text instead of the Material Icon. import React, ...

Can you explain how to utilize theme values in CSS within Mui?

Working on my React app with mui themes, I have the following in index.js: let theme = createTheme({ palette: { primary: { main: "#00aaa0", contrastText: '#fcf4d9', }, secondary: { main: "#D55B3E&quo ...

Why aren't my Post Variables being passed through my jQuery Ajax Request?

My goal is to utilize a full calendar ajax call to add events to the database. After testing the PDO query separately and confirming its functionality, I have identified an issue with the ajax post. The code snippet below showcases the ajax call in defaul ...

What are some strategies I can implement to effectively manage different errors and ensure the app does not crash

I came across a variety of solutions for error handling. The key concept revolves around this explanation: https://angular.io/api/core/ErrorHandler Attempts were made to implement it in order to capture TypeError, however, the outcome was not successful: ...

tips on displaying a div dynamically in a specific location

Currently, I have implemented HTML textBoxes on my website. However, I am looking to validate these textBoxes using JavaScript. Rather than displaying a traditional alert popup for invalid data input, I would like to show a div next to the specific textBox ...

React - the function executed within a loop is only invoked once

I have implemented a click handler in my book component to facilitate page flipping. This handler appends the necessary classnames to the pages, enabling me to set up the CSS for the page flip animation. // ---------- Handle the click event on the book p ...

Creating a dynamic table using jQuery and XML content

Hello everyone, I am new to jQuery and JavaScript in general. My goal is to generate a table based on XML data, but I'm struggling to achieve the correct output. Here's what I have tried so far: Here is my HTML code: <table id="daily_fruit"& ...

Why doesn't the 'javascript' named directory have access to my localhost?

My Ubuntu 16.04 system is running Apache 2.4.18. Recently, I created a directory called "javascript" within /var/www/html and added an HTML file to it. However, when attempting to access the file via localhost/javascript/, I received the following error me ...

Deactivate radio buttons when the table value is greater than or equal to one

On my webpage, there are radio buttons for 'Yes' and 'No'. When 'Yes' is selected, a hidden <div> appears where users can fill in fields. Upon clicking the 'Add' button, the information is displayed in a table. ...

JavaScript that is subtle and lacks function parameters

Suppose you have: <div id="data" onclick="handleData(1)">Datum 1</div> and you prefer late binding instead: <div id="data">Datum 1</div> <script> $("#data").click(function() { handleData(1); }) </script&g ...