11

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,963
  • 19
  • 86
  • 127
Mercurial
  • 3,615
  • 5
  • 27
  • 52
  • 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

3 Answers3

19

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,963
  • 19
  • 86
  • 127
  • `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
  • 2,248
  • 4
  • 20
  • 35
1

Be patient, trust me, you need to modifiy the style tag's textcontent.

 // add style tag
export function addFontSizeModeStyle(modeStr: EFontSizeMode) {
  const sizeObj = SIZE_MODE_DATA[modeStr]?.size
  if (!sizeObj) return
  appendStyle({ id: FONT_STYELE_ID, cssStr: `:root{${filterStyleStr(JSON.stringify(sizeObj))}}` })
}

// handle :root  format
function filterStyleStr(txt: string) {
  return txt.replace(/\"/gi, '').replace(/\,/gi, ';').replace(/{|}/gi, '').concat(';')
}

// create style tag
function appendStyle({ id = '', cssStr }: { id?: string; cssStr: string }) {
  const styleEl = document.createElement('style')
  styleEl.type = 'text/css'
  styleEl.id = id
  styleEl.textContent = cssStr
  document.head.appendChild(styleEl)
}

// set fontSize mode
export function setFontSizeMode(modeStr: EFontSizeMode) {
  const sizeObj = SIZE_MODE_DATA[modeStr]?.size
  if (!sizeObj) return
  let $style = document.querySelector(`#${FONT_STYELE_ID}`)
  const cssStr = `:root{${filterStyleStr(JSON.stringify(sizeObj))}}`
  if ($style) {
    $style.textContent = cssStr
  } else {
    appendStyle({ id: FONT_STYELE_ID, cssStr })
  }
  window.localStorage.setItem(FONT_THEME, modeStr)
}

usually, we can find the answer how to change css :root variable, it is

 // not good
document.documentElement.style.setProperty(key, value)

but works on html tag's inline style in essence, use the level to cover :root variable, not change its variable enter image description here enter image description here

George Wayne
  • 160
  • 1
  • 5