Mercurial
Mercurial

Reputation: 3885

Change CSS root variable with jquery or javascript

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?

Upvotes: 13

Views: 24304

Answers (3)

George Wayne
George Wayne

Reputation: 191

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

Upvotes: 1

UselesssCat
UselesssCat

Reputation: 2406

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!

Upvotes: 11

caramba
caramba

Reputation: 22490

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>

Upvotes: 21

Related Questions