Using jQuery to dynamically insert variables into CSS styles

I am attempting to use jQuery 3 to modify the CSS of a class and change the background color.

My first step is converting an rgba color code (properties.color) to a hexadecimal code, which is functioning correctly.

Next, I try to change the background color of the "zu-default div" class using jQuery. However, when I use the variable "finalcolor", the change does not take effect. Strangely, if I hardcode a hexadecimal color like "#fec23b", the change is visible. When I check the console, it confirms that the variable finalcolor contains a valid hexcode.

Any suggestions on what may be causing this issue?

// convert rgba to hex
let finalcolor = rgb2hex(properties.color);

// print the converted hexadecimal value (e.g. #fec23b)
console.log(finalcolor);

// should change the background of the zu-default div class to the color specified in "finalcolor"
$('.zu-default div').css("background", finalcolor);

Answer №1

$('.zu-default div').css("background", finalcolor+' !important');

or

$('.zu-default div').css("background", finalcolor.toString());

Does this code work as intended?

 $('.zu-default div').css("background", 'green');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="zu-default">
            <div style="width: 10px; height: 10px;"></div>
            <div style="width: 10px; height: 10px;"></div>
            <div style="width: 10px; height: 10px;"></div>
        </div>

let finalcolor = '#222222';

$('.zu-default div').attr('style', $('.zu-default div').attr('style')+"background: "+finalcolor+";");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


        <div class="zu-default">
            <div style="width: 10px; height: 10px;"></div>
            <div style="width: 10px; height: 10px;"></div>
            <div style="width: 10px; height: 10px;"></div>
        </div>

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

Using Javascript to display an element when scrolling within a specific container and each item of an array reaches the top

I'm just starting out with JavaScript and I'm attempting to create a scrollable div that includes items from an array. As the user scrolls and each item reaches the top, I want a hidden element to be displayed. Here's what I have so far: ...

The success notification transforms into a cancellation alert once the file has been successfully uploaded

I'm struggling to show the correct message after a file is successfully uploaded. Currently, when a file is successfully uploaded, the success message briefly displays but then quickly changes to the cancel message. I want the success message to rema ...

Show the comment section only if the initial radio button is selected

I am struggling to implement a comment section that is displayed when the first radio button is checked. Here's the code I have tried: I attempted the following to show the section and test the associated script: <div id="commentaryDiv" ...

random mongoose response 500

I came across a nodeJS code recently that was supposed to retrieve random documents from my mongoose collection using the mongoose-random plugin. However, whenever I call the findRandom() method, it returns a 500 error. test.js Below is the code snippet: ...

Tips for avoiding flickering in safari during @-webkit-keyframe animations

At times, Safari may experience flickering during the execution of a CSS animation. Despite extensive research and attempts to find a solution, the issue persists. The HTML code snippet is as follows (refer to jsfiddle for more details) <div class="do ...

Ways to discover the titles of every sub-directory

Suppose I have the absolute path of a directory. Is there a method in JavaScript (Node.js) to determine how many sub-directories it has, and retrieve the names of all its sub-directories? I searched online but didn't come across any solution. ...

Modify the color of the div element after an ajax function is executed

My original concept involves choosing dates from a calendar, sending those selected dates through ajax, and then displaying only the chosen dates on the calendar as holidays. I aim to highlight these selected dates in a different color by querying the data ...

Whenever I open my collapsible dropdown, it seems to leap up unexpectedly

When I interact with the collapsible card, it has a jerky animation. I would like it to open smoothly instead. The issue lies with the tooltip-cus class. If I remove position: relative;, the opening animation is smooth, but then the position of the toolti ...

Interacting with HTML elements in Java programming

I am facing a challenging situation that requires some brainstorming. I would greatly appreciate any advice or guidance in the right direction. My goal is to incorporate a Google Map into my Java Swing project, with the map being specified as a URL wit ...

Preventing Height Stretch in CSS Flex-Wrap: A Guide

Is there a way to eliminate the large gaps between box3, box1 and box4, box6? How can we ensure each box adjusts its height dynamically? .wrap { display: flex; align-items: baseline; align-content:flex-start; justify-content: space-between; fl ...

Is there a way to navigate to the home page using a PNG icon without refreshing the page when clicked on, while also utilizing NavLink with a route of '/'?

Here's the code I'm working with: <div key="1" className="menu-item"> <NavLink to="/"> <span className="icon-home3" />&nbsp; Home </NavLink> </div> The Home button functions ...

Is there a way to always keep an element positioned directly above a fluid image that is perfectly centered?

My current project involves creating an overlay to display a fluid image of any size. The challenge I'm facing is how to consistently position the close button 30px above the image and flush with its right edge. The catch is that the container doesn&a ...

The icon displays correctly in Firefox but is not visible in IE

link REL="SHORTCUT ICON" HREF="/images/greenTheme/favicon.ico" type="image/x-icon" While this code functions properly in Firefox, it appears to be causing issues in Internet Explorer. Can anyone provide guidance on how to resolve the compatibility issue w ...

Is it a good idea to resize images sourced from other websites before displaying them on your

I am currently working on a project that involves fetching images from various websites and displaying a thumbnail or resized version of the original image. Since I will be fetching many images at once, loading the original image files can take longer. ...

Firefox experiencing trouble handling flexbox overflow

Having some trouble with a test project that involves using flexbox. The task at hand is to create a dashboard with multiple lists of cards arranged side-by-side with infinite overflow. I was able to achieve this layout, however, the issue arises when eac ...

How can I convert the left links in my navigation bar to a CSS drop-down menu to make it more responsive on small screens?

Here is the structure of my HTML (at the top): <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></s ...

Deliver an assured result to a variable within the angular.extend() function

Can someone provide guidance on how to set myVar to a value returned from an asynchronous service method in the following example? angular.extend(this, { myVar: (function() { getVal(); })() }); function getVal() { var d = $q.defer(); ...

Rotation to a point in a circle using three.js

Currently, I am in possession of 2 instances of THREE.Vector3(). My task at hand is to create a circular shape around one vector with the second vector serving as a tangent. I have determined the radius of the circle geometry based on the distance betwee ...

Troubleshooting issues with the IE flexible box model functionality

Working on incorporating the flexible box model into my website has been a bit challenging. It seems to function well in webkit-based browsers like Chrome and Safari, but I'm running into issues with Mozilla, Opera, and most notably Internet Explorer. ...

Creating Location-Specific Customer Data using AngularJS similar to Google Analytics

Looking to create a user registration map similar to Google Analytics without actually using Google Analytics. Can anyone provide assistance with this task? I am utilizing MVC, C#, Sql Server-2014, AngularJS, and jQuery for this project. Despite my efforts ...