13

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?

1

3 Answers 3

21

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>

Sign up to request clarification or add additional context in comments.

3 Comments

document.documentElement.style.setProperty('--themeColor', '#' + ("000000" + Math.random().toString(16).slice(2, 8).toUpperCase()).slice(-6)); Will this work?
@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 . . .
@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); }
11

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!

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.