Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating the same 2 random colors for 2 different objects

Basically, I have to generate the same color, chosen randomly, for 2 different bodies. Does anyone have any tip on how I could link the two objects to have the same random colour? Evertime a condition happens, the colour should refresh and both bodies should have that particular colour. Thx a lot! //btw any code language is useful

like image 359
Jason Nieman Avatar asked Jan 12 '21 22:01

Jason Nieman


2 Answers

The simple solution is to generate the random color once and then set the color of both bodies to that color. Put that in a refreshColors function and call that function when your condition is met.

if (condition) {
  refreshColors()
}

function refreshColors () {
  // generate color
  let color = generateRandomColor()

  // set Body A color
  body_a.style.color = color

  // set Body B color
  body_b.style.color = color
}
like image 56
cam Avatar answered Sep 19 '22 12:09

cam


I recommend using a custom property (also known as CSS variables):

function randomColor() {
  const r = Math.floor(Math.random() * 256);
  const g = Math.floor(Math.random() * 256);
  const b = Math.floor(Math.random() * 256);
  
  return `rgb(${r},${g},${b})`;
}

const root = document.documentElement;

root.style.setProperty("--random-color", randomColor());
.element-1,
.element-2 {
  background-color: var(--random-color);
}
<p class="element-1">Element 1</p>
<hr />
<p class="element-2">Element 2</p>

If you want you can set the custom property to some default value in your CSS file:

:root {
  --random-color: rebeccapurple;
}

And make sure your elements use this property, using the CSS var() function:

.element-1,
.element-2 {
  background-color: var(--random-color);
}

Then you overwrite that property in you if statement using style.setProperty:

if (condition) {
  const root = document.documentElement;
  root.style.setProperty("--random-color", randomColor());
}

Read more about dynamically setting custom properties in this article.

like image 40
Rúnar Berg Avatar answered Sep 19 '22 12:09

Rúnar Berg