Is there a way to incorporate pseudo-dynamic css into my projects?

I'm struggling with managing custom colored elements on my website.

For instance, I have a hundred navigation squares on the site, each with its own unique color. The only solution I can think of is creating separate CSS classes for each color, but that will result in an overwhelming amount of CSS code.

Any help or suggestions would be greatly appreciated. Thank you!

*I've added JavaScript & JQuery tags as possible solutions to this issue

Update: Thank you for all the responses. To provide more context, I have square category navigation on my search page where colors can either come from the server side or be stored in client-side JS. I receive a list of categories from the server (each with an assigned color), and then I create all the squares. By default, they are white but change color on hover. Here's how I currently approach this:

<ul id="squares">
<li class="greencolor"></li>
<li class="redcolor"></li>
<li class="bluecolor"></li>
</ul>

Using CSS:

#squares li.redcolor:hover{
 background:red;
}
#squares li.greencolor:hover{
 background:green;
}
#squares li.bluecolor:hover{
 background:blue;
}

As you can see, this approach results in a lot of CSS code for 100 elements.

While I understand I could use a solution like this:

var colorsMap={'redcolor':'red','greencolor':'green'};     
$('#squares li').on('hover',function(e){

    $(this).css('background-color', colorsMap[$(this).attr('class')];

});

I don't find it elegant and prefer finding a way to handle this through CSS rather than inline JS changes.

Answer №1

It is suggested to utilize CSS for accomplishing this, but there exists a superior alternative to inline styling:

var selector = '#squares li'
  , css = []
  , style = document.createElement( 'style' )
  , colorsMap= {
      'redcolor': 'red',
      'greencolor': 'green',
      'bluecolor': 'blue'
    }
$( selector ).each( function() {
  css.push( selector + 
            '.' + 
            // recommend using data-attr for storing color information
            // assuming `className == 'bluecolor'`
            this.className + 
            ':hover' +
            '{' +
            'background:' +
            colorsMap[ this.className ] +
            '}'
            )
})
style.textContent = css.join('')
document.head.appendChild( style )

By dynamically inserting CSS into <head>, you can still enjoy the advantages of standard CSS, demo.

Furthermore, you have the option to generate dynamic CSS files on the backend, making it easier to manage colors through a configuration form or other means.

Answer №2

Although my English skills are still a work in progress, I am dedicated to improving them. I may not fully comprehend your message, but it did bring to mind the concept of the chooser. While I can't be sure if this is what you intended, I believe it's worth exploring. Some examples include:


    $(":header").css("color","#FF00FF");<br>
    $("div:contains('test')").css("background","#666600");<br>
    $("div:empty").css("background","#888800");<br>
    $("div:has(span)").css("background","#008080");
    
and more.
I won't delve into their specific roles, but I find them essential for learning and incredibly beneficial.

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

Exploring the limitations of middlewares in supporting independent routers

When I examine the code provided, it consists of three distinct routers: const Express = require("express") const app = Express() // Three independent routers defined below const usersRouter = Express.Router() const productsRouter = Express.Router() cons ...

Unable to implement CSS styles on the provided HTML code

I'm currently working on integrating evoPDF into my asp.net application. When I click on a part of the HTML file, I send that portion using AJAX. So far, everything is working well up to this point. However, when I try to use the following methods fro ...

What is the best location for implementing role-based authentication in a MeanJS application?

I am working with a meanJS starter template that includes a yeoman generator. I'm trying to figure out where I can add specific permissions to my modules. For example, 'use strict'; // Configuring the Articles module angular.module(' ...

Perform Jquery trigger on mobile by clicking, and on desktop by hovering

Despite encountering this question numerous times, I am still unable to find a solution. I have a dropdown menu and I want it to open on hover for desktop and on click for mobile devices. I attempted using the provided code, however, it only works after r ...

Tips for streamlining distinct states and generalized state in UI Router

I've set up the following configuration in my JS app under the $stateProvider section using angular ui-router: .state('login', { url: '/login', templateUrl: 'app/login/login.tmpl.html', controller: &apo ...

Adjust the database table when a session expires in PHP

Within my PHP code, there is a session timeout feature that triggers after 60 minutes of inactivity. This code snippet resides in the file /mno.php, where both the login and logout functionalities are also implemented. /mno.php if (isset($_SESSION[' ...

There seems to be an issue with the next function's functionality within a Nodejs middleware

Currently, I am delving into the world of Nodejs with expressjs. My focus is on understanding middleware functions and specifically, the role of "next". In the middleware concept, "next" simply moves on to the next middleware in line. So, what exactly is ...

What is the best way to enhance an object using a class in ES6?

In an effort to improve the clarity of my ES6 class definition, my current code looks like this: class SomeClass { constructor({a, b, c, d, e}) { this.a = a; this.b = b; this.c = c; this.d = d; this.e = e; // additional code here ...

The NPM version needs to be updated as it is outdated

Struggling with a dilemma here. My Laravel project is quite dated, and I'm unable to execute npm run dev. Let's take a look at some code: php artisan laravel --version: Laravel Framework 5.8.38 node --version: v16.16.0 This is the current Node v ...

Defining the active element in the menu using JavaScript

I need help with my navigation menu: <ul> <li id="active"><a href="/">Home</a></li> <li><a href="/about/">About Us</a></li> <li><a href="/services/">Our Services</a>< ...

Using jQuery Flot to dynamically load data onto the x-axis from an array

I have a jQuery flot graph that loads the x-axis data as follows: xaxis: { tickColor: 'transparent', tickDecimals: 0, ticks: ticks }, When I manually set the ticks variable like this, everything works fine and the x-axis displays the 7 da ...

How to Detect Font Resizing in Google Web Toolkit (GWT)

I am trying to find a way in GWT to capture the font resize event that occurs when the user changes the size of the font by using Ctrl-Mouse Scroll or going to View -> Zoom. I have searched on Google and looked on StackOverflow but haven't found any i ...

Tips for converting asynchronous function calls into synchronous functions in Node.js or JavaScript?

Imagine you are managing a library that provides access to a function called getData. Users utilize this function to retrieve real data: var output = getData(); In the background, the data is stored in a file, so you have implemented the getData functi ...

What is the best way to use jQuery to filter data in a table by clicking on a specific table row?

My website contains a table with player names and servers, but I want to make them clickable for filtering purposes. For instance, clicking on a player name should reload the leaderboards to show which servers that player plays on, and clicking on a server ...

Tips for integrating google's api.js file into my vue application

Currently, I am in the process of integrating Google Calendar into my Vue project. The steps I am following can be found at this link. Additionally, I came across an example code snippet at this URL. This is how my Vue file looks: <template> <d ...

Tips for displaying a category name only once if it has already been rendered in a map function

My scenario involves a variety of categories in which pharmaceutical drugs are classified. Each individual drug belongs to a specific class. Currently, my code iterates through all the categories from the category array and places drugs underneath them if ...

Web Browser Fails to Set Cookie during an Ajax Request

I am facing a perplexing issue. I have an AJAX call that triggers the processing of a login form and generates a cookie upon successful login. However, the web browser is failing to recognize the cookie. Upon troubleshooting, I have narrowed it down to so ...

The array element is not being shown in the id "main" when using a for loop with the onchange function

I've been using document.write to display specific content, but it seems to be removing other elements from the page. Is there a way for me to display this loop inside the element with id="main" without losing any content? When I attempt to use docume ...

Sending a string array to MVC controllers through ajax

I've been struggling to pass a list of strings from a multiple select to the controller. Despite seeming like a simple requirement, I've spent hours trying to figure it out without success. I've done some research on this but haven't be ...

Creating a toggle label using just CSS: a step-by-step guide

Recently, I was trying to create a toggle label using HTML, CSS, and JavaScript. Here is the code snippet that I experimented with: function genre_itemclick(item){ if(item.classList.contains('light_blue_border_button')) { ...