<button onclick="setBackgroundGreen()">Set background lightgreen with JavaScript</button>
<code> --bg-color =
<span id="result"></span>
</code>
<p>Rerun the pen to see it again</p>
<a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties" rel="nofollow noopener" target="_blank">MDN Docs</a>
:root {
/* See what happens when you uncomment the below line to simulate what would happen if --bg-color was already set - rerun the pen once uncommented */
/* --bg-color: yellow; */
}
body {
background: var(--bg-color, lightblue);
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
gap: 1rem;
min-height: 100vh;
}
button {
border: 1px solid transparent;
background-color: #ddd;
padding: 1rem;
cursor: pointer;
border-radius: 15rem;
}
button:hover {
border-color: #000;
}
a {
color: dodgerblue;
transition: all 160ms ease;
}
a:hover {
color: darkorange;
}
const setBackgroundGreen = () => {
document.documentElement.style.setProperty("--bg-color", "lightgreen");
getBgColor();
};
const getBgColor = () => {
const bgColor = getComputedStyle(document.documentElement).getPropertyValue(
"--bg-color"
);
document.getElementById("result").innerText =
bgColor === "" ? "undefined" : bgColor;
};
getBgColor();
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.