10

I am using CSS variables in my webpage and making a sort of theme color,

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

Now i've used var(--themeColor) everywhere and i want to assign a random color to --themeColor at every reload. Is this possible?

caramba
  • 21,282
  • 18
  • 84
  • 125
Mercurial
  • 3,145
  • 5
  • 24
  • 47
  • Does this answer your question? [Modify CSS variables / custom properties in jQuery](https://stackoverflow.com/questions/49048192/modify-css-variables-custom-properties-in-jquery) – ashleedawg Jan 07 '22 at 13:39

2 Answers2

18

You can do this pretty easy with something like:

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

Update: Not sure if the question was just about changing the color as I thought. Now I've also added a getRandomColor() example. Just to get random stuff can be a big load of work depending if you want to save 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>
caramba
  • 21,282
  • 18
  • 84
  • 125
  • `document.documentElement.style.setProperty('--themeColor', '#' + ("000000" + Math.random().toString(16).slice(2, 8).toUpperCase()).slice(-6));` Will this work? – Mercurial Nov 13 '16 at 09:47
  • @unkn0wn maybe kind of but you don't get all colors. HEX colors go from `0 - F` that's why `white` is `#FFFFFF`. I would define an array of colors. Imagine also the difference from `#010101` and `#000000` is almost not visible for us humans and now you could even get `#000001` . . . – caramba Nov 13 '16 at 09:52
  • @unkn0wn if you want to create random colors like that try with `rgb()` or `rgba()` which is CSS and each value goes from `0 - 255` if using `rgb()` and the `a` from `rgba()` goes from '0 - 1` for `opacity` so `a { color: rgba(100, 100, 100, 0.7); }` – caramba Nov 13 '16 at 09:57
8

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

$(':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 on all versions of JQuery!

UselesssCat
  • 1,929
  • 3
  • 17
  • 33