Changing CSS root variable using jquery or javascript

I use CSS variables on my web page and do some sort of theme color,

:root { --themeColor: #0afec0; --hoverColor: #fff; --bodyColor: #EEF1EF; } 

Now I have used var(--themeColor) everywhere, and I want to assign a random color --themeColor every time I reboot. Is it possible?

+5
source share
2 answers

You can do this quite easily with something like:

 document.documentElement.style.setProperty('--themeColor', 'red'); 

Update: Not sure if the only question is to change the color as I thought. Now I have added the getRandomColor() example. Just getting random things can be a big load of work depending on if you want to keep the last used color by the user or so ...

 // array with colors var colors = [ "red", "green", "lime", "purple", "blue" ]; // get random color from array function getColor() { return colors[ Math.floor(Math.random() * colors.length) ]; } // Set the color from array document.documentElement.style.setProperty('--themeColor', getColor()); 
 :root { --themeColor: orange; } a { color: var(--themeColor) } div { width: 100px; height: 100px; background-color: var(--themeColor); } 
 <a href="#">Hello world</a> <div>Test</div> 
+5
source

You can do this in jquery as follows (using the same caramba example):

 $(':root').css('--themeColor', (color = ["red", "green", "lime", "purple", "blue"])[Math.floor(Math.random() * color.length)]); 
 :root { --themeColor: orange; } a { color: var(--themeColor) } div { width: 100px; height: 100px; background-color: var(--themeColor); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <a href="#">Hello world</a> <div>Test</div> 

This may not work in all versions of jQuery!

0
source

Source: https://habr.com/ru/post/1259665/


All Articles