Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying CSS by inserting variable with jquery

I am trying to modify the css of a class using jquery 3 and change the background color.

First I am converting a rgba color code (properties.color) to a hexadecimal code which works perfectly fine.

I then change the background of the „zu-default div“ class using jquery. This however does not work when I insert the variable „finalcolor“. When I hardcode a hexadecimal color such as „#fec23b“ , the change is visible. When I use the variable „finalcolor“ there is no change. Printing the variable finalcolor to the console shows that is a perfectly fine hexcode.

Any suggestions?

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

    //prints the converted hexadecimal (for eg: #fec23b)
   console.log(finalcolor);

//Should modify the background of the zu-default div class to the color „finalcolor“
$('.zu-default div').css("background", finalcolor);
like image 597
NL97 Avatar asked Jun 07 '26 06:06

NL97


1 Answers

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

or

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

it is Working?

 $('.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>
like image 91
Юрий Светлов Avatar answered Jun 10 '26 19:06

Юрий Светлов