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

What is the process for inspecting the element within a div using jsname with JS?

Struggling to inspect elements within a DIV without using xpath. // Assert.assertEquals("Digite uma senha",driver.findElement(By.xpath("//*[@id=\"view_container\"]/div/div/div[2]/div/div[1]/div/form/span/section/div/div/div[1]/div[2]/div[2] ...

Integrate functionality to track elapsed hours in stopwatch timer

Struggling to incorporate hours into my JS Stopwatch timer, the math for calculating the hours section is proving difficult. This is what I have so far, but I suspect the issue lies within the h variable. function formatTime(time) { var h = m = s = ...

What is the best way to make an element fixed vertically in a mobile browser while also enabling horizontal scrolling?

When using a Desktop browser, I have found a javascript code that allows me to vertically fix an element while still enabling horizontal scrolling. The element is repositioned with each scroll event. You can test this out by trying both horizontal and vert ...

Unable to set DIV to 'inline-block' or none based on checkbox selection

Despite reviewing multiple examples, I am still struggling to make this DIV visible and hidden by clicking a checkbox. Can someone please review my JavaScript code? <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Conten ...

Are Primereact and MUI JOY Styling at Odds?

here is the image of datatables and button I am currently using Primereact and MUI Joy in the same project, but I am facing an issue where the Primereact styling does not load properly. I'm not sure if it's due to a conflict with MUI Joy or some ...

``Is it possible to adjust the style of an HTML element based on the style of another element?

Within my web application, I am dynamically changing the style of an HTML element using JavaScript. Below is the code snippet: function layout() { if(document.getElementById('sh1').getAttribute('src') == "abc.png") { docum ...

CORS issue encountered by specific user visiting the hosted website

I recently developed a bot chatting website using Django and React, which I have hosted on HOSTINGER. The backend is being hosted using VPS. However, some users are able to see the full website while others encounter CORS errors where the APIs are not func ...

Tips for allowing a position:absolute <div> to expand as though it were containing a lengthy <p>innerText

This div automatically adjusts its width to fit the content inside, even if it extends beyond the page boundaries. Is there a way to make this div expand to fill the entire width of the page without needing a paragraph? <div style="position:absolute;le ...

Continuously spinning loading icon appears when submission button is triggered

We are currently experiencing some issues with our mobile forms. Our users utilize a mobile form to submit contact requests, but the problem arises when they hit 'submit' - the loading icon continues to spin even after the form has been successf ...

Images are not being shown on the desktop carousel display

I am encountering an issue with my carousel. When I attempt to decrease the height of the carousel, the entire image is not being displayed properly (on desktop), although it works fine on mobile devices. My goal is for the carousel not to take up the ent ...

Storage in private Safari mode is not synced between tabs on mobile devices

In the private mode of mobile Safari, I have successfully stored data in the localStorage. However, when I open my web app in two separate tabs, I notice that the data stored in one tab is not accessible in the other tab. This behavior may be present in ot ...

Tips for preventing the colors of all buttons from changing when only one is clicked in JavaScript

const tasks = `[{ "taskName": "Task 1", "image": "./images/task1.jpg", "description": "Task 1 description", "importance": 0 }, { "taskName": "Task 2", "image": "./images/task2.jpg", "description": "Task 2 description", ...

Creating a sleek horizontal drop-down navigation menu using Bootstrap 5 and CSS

Attempting to design a horizontal dropdown menu for small screens has been a challenge. However, all the resources I've come across seem to be outdated and ineffective. ...

The HTML body is given a right margin for proper spacing

Within the page, I noticed some margin to the right that extends beyond the body itself, causing a scroll bar to appear at the bottom. However, I'm unable to determine the root cause of this issue. I have provided links to both Codepen and Netlify be ...

Ways to verify and incorporate https:// in a URL for a MEAN Stack application

When extracting the URL from API data, my code looks like this: <div class="row copy-text"> <a href="{{copy.Url}}" target="_blank" style="text-decoration: underline !important;">{{copy.Title}}</a> </div> I am interested in ve ...

Issues with the styling of a CSS webpage within an AJAX application

I'm encountering an issue with my CSS style that works fine on a static HTML page. The problem arises when content is dynamically loaded into layer3 and then into layer 2. I'm struggling to understand the consistency as sometimes the layers are ...

Receive Real-Time Notifications -> Update Title Using an Array Retrieved from a JSON File

I've been working on updating a live chart every 5 seconds with new data from the database. While I could easily update the information, I encountered a problem when trying to set a path within the chart options for tooltips callbacks afterTitle. Spec ...

Is it possible to use JavaScript to clear a field that was generated by Yii CRUD?

Issue with Yii's GRUD field generated and Firefox HTML: <?= $form->field($model, 'productId')->textInput(['maxlength' => true]) ?> Comparison of PHP generated code to Firefox HTML: <input id="taolistforcreate-p ...

Issue: [$injector:unpr] Provider not found: RequestsServiceProvider <- RequestsServiceFor more information on this error, please visit the website: http://errors.angularjs.org

Despite defining my service name in all necessary places, I am still encountering the error mentioned above. Below is my app.js: var app = angular.module('ionicApp', [ 'ionic', 'ngCordova', 'checklist-model' ]) ...

Interested in trying out Express and socket.io for chatting?

I've successfully set up the chat application, but now I'm faced with a dilemma: how can I make the chat work on the default port:80, where my main site is hosted? One solution that comes to mind is using an iframe - but is there another way? B ...