Reputation: 91
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
Upvotes: 7
Views: 911
Reputation: 4812
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.
Upvotes: 4
Reputation: 3616
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
}
Upvotes: 4