Any tips on how to effectively integrate dynamic theming in CSS?

I am currently developing a theming feature for my web application, allowing users to select a theme that will dynamically change the color of various elements. Here is an example of the theme selector:

<div id="theme-selector">
  <div id="theme-red" class="theme"></div>
  <div id="theme-purple" class="theme"></div>
</div>

Once a user selects a color, a class is added to the body element:

$(document).on('click', '.theme', function(e) {
  var color;
  color = this.id;
  $('body').removeClass();
  $('body').addClass(color);
});

The process becomes cumbersome when dealing with CSS because you have to repeat selectors for each color scheme:

/* Red theme */
body.theme-red header, body.theme-red .button-primary {
  background-color: #ff0000;
}
body.theme-red .button-primary:hover {
  background-color: #cc0000;
}
body.theme-red a {
  color: #ff0000;
}

/* Purple theme */
body.theme-purple header, body.theme-purple .button-primary {
  background-color: #800080;
}
body.theme-purple .button-primary:hover {
  background-color: #993399;
}
body.theme-purple a {
  color: #800080;
}

Although using variables in pre-compilers like LESS or Stylus can help streamline the process, it does not address the issue of code repetition.

Are there any better, more programmatic techniques for implementing dynamic theming?

Answer №1

Changing the color using javascript while handling color selection can be more convenient. Simply use a set of css classes like textcol and linkcol and apply them dynamically with javascript. Only two lines of css code are needed for this, without relying on jquery or other dependencies.

a, .linkcol {text-decoration:none;}
.big { font-size:1.2em;} 
<!DOCTYPE html>
<html>
<body>
<h1>Hello world</h1>
<p>Click the button to change the theme.</p>

<button onclick="colFunction('#808000','#000000')">Green</button>
<button onclick="colFunction('#800000','#666666')">Red</button>

<p id="demo">This <a class="linkcol" href="#">link</a> and <span class="big linkcol">these big words</span> which use multiple classes should be black except for red theme, which makes them gray</p>

<script>
function colFunction(textcol, linkcol) {
    document.getElementsByTagName("body")[0].style.color = textcol;
for (i=0;i <= document.getElementsByClassName("linkcol").length;i++)  {
    document.getElementsByClassName("linkcol")[i].style.color = linkcol;
    } 
}
</script>

</body>
</html>

Explanation

If desired, HTML can be edited to add extra classes for individual elements, as demonstrated by the example of <span class="big textcol">. Setting the main color for the <body> tag will result in all elements inheriting the color, unless they have their own default colors (<a> being an exception).

User-defined colors

By utilizing javascript arguments, users can input their preferred colors via textbox or dropdown menu. This allows users to customize colors beyond those predefined by simply calling the javascript function with variables instead of specific hex values.

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

Flask does not provide a direct boolean value for checkboxes

After struggling for a week, I am still lost on where to make changes in my code. I need the checkbox to return a boolean value in my Flask application. Below are snippets of the relevant code: mycode.py import os, sqlite3 from flask import Flask, flash ...

Troubleshooting a Problem with the Horizontal Scrollbar in Dynamic jqGrid

Currently, I am working on an ASP.net MVC project where I have implemented both dynamic and static jq grids. However, I am encountering an issue with the horizontal scroll bar in my application. To address this problem, I attempted to modify the overflow ...

Submit Button Field - HTML ButtonFor

Being relatively new to MVC Razor and web development, both front-end and back-end, I'm in need of a button that can send a stored value to the controller/model. I attempted to mimic the functionality of Html.TextBoxFor by giving it attributes similar ...

Create an array by utilizing a variadic template list and implementing placement new

I've been working on implementing the following function: template<typename T, typename... ARGUMENTS> std::unique_ptr<T[], HeapDeleter<T[]>> allocate_array(ARGUMENTS&&... arguments) { HeapAllocator<T> allocator; ...

Adding arrays from SQL results to an array in an iterative manner

Hello everyone, I am a newcomer here and have been enjoying reading through the various questions and answers provided. As someone fairly new to PHP, I am currently working on a project that involves basic table look-ups in MySQL. My goal is to create ...

Measuring JSON data with PHP through asynchronous requests

Looking to retrieve a specific count from a json dataset. Here is an example json format: { "tickets": [ { "url": "https://asd.zendesk.com/api/v2/tickets/1.json", "id": 1, "external_id": null, "via": { "channel": "sa ...

Issue with accessing $index.$parent in function parameter within ng-repeat in AngularJS

Can anyone with more experience please explain to me why this particular code compiles successfully: <li class="btn dropdown top-stack breadcrumb-btn" ng-repeat="nodeName in selectedNodeNames"> <a class="dropdown-toggle btn-anchor"> ...

What are the advantages of combining a library (using Rollup or Webpack) instead of simply transpiling it with Babel?

When developing a library in JavaScript, what are the benefits of using tools like Rollup or Webpack for bundling rather than just transpiling with Babel? One potential advantage could be that by bundling, you ensure that your dependencies are packaged eff ...

Improve numerous conditions

I am currently working on a project that involves Angular and Node. In this project, I have written a function with multiple if and else if statements containing various conditions. The code looks complex and lengthy, and I want to refactor it to make it ...

Using a PHP variable to dynamically change the style sheet by connecting to a MySQL database

My goal is to have the stylesheet URLs stored in a database and be able to change the stylesheets' href using variables in HTML tags. However, when I tried the following code, nothing happened: global $theme_addresss; global $showdetail_dbtadbiruse ...

Troubleshooting a problem with selecting options in Jquery

Looking for assistance with a jquery script. I have a select dropdown that fetches a list of options via Ajax. When a user clicks on an option, if a certain variable equals 1, an HTML div is added. If the variable changes to another value, the HTML div dis ...

What is the best way to add a sliding effect to this presentation?

https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_slideshow I am attempting to create a sliding effect for image transitions instead of the typical fade in and out. However, I'm uncertain about how to approach this challenge. My concept i ...

Attempting to utilize solution for the "ajax-tutorial-for-post-and-get" tutorial

I've been exploring the implementation of the second answer provided in a post about Ajax tutorials on a popular coding forum. Despite following the instructions, I encountered an issue where the $.ajax script, triggered by an "onclick" function, only ...

Populating a 2D array using elements from a different array

I'm currently working on populating a 2D array using a for loop, with a variable that is an array. My goal is to calculate the average of each column from this array and store it in a new array. However, I'm facing a challenge on how to insert t ...

What is the best method to calculate the total of multiple input values from various cells and display it in the final cell of an Angular table?

Hey there! I have a challenge where I need to calculate the sum of input values for each cell and display it dynamically in the last cell of the row. Take a look at the image below: https://i.stack.imgur.com/0iKEE.png In the image, you can see that the nu ...

Saving text as an array with: Mongoose, MongoDB, and SimpleDB-mongoose

Within my schema, I define the following: Links: [] When working with a post request in Node.js, my code looks like this: app.post('/add', function (req, res) { var newItem = new db.Item({ Links[0]: req.body.Link1 Links[1]: req.bo ...

Achieving synchronization within the 'it' block using Protractor

I am currently experiencing synchronization issues in the 'it' block of my code. The following snippet illustrates the problem: it('Some Download Operation',function() { console.log("before"); myobj.clickOnDownloadBtn(); ...

I'm a bit torn between using images for text or utilizing Google Fonts

I am looking to use a unique font that is not commonly used. This font is available in Google Fonts as well as in Photoshop. I am unsure about which method to choose because both options involve some loading time. Although using images for text is not idea ...

What are the solutions to resolving issues that arise from using a numpy array in an if condition?

Seeking to iterate through each element of "z" using an "if else" condition and return the desired equation, my current implementation is yielding an error. I have experimented with the "z.all" and "z.any" functions, but both are converting "z" into a bool ...

Node JS Client.query not returning expected results

Currently, I am developing a Web Application that interacts with my PostgreSQL database. However, when I navigate to the main page, it should display the first element from the 'actor' table, but unfortunately, nothing is being retrieved. Below i ...