Skip to content

Instantly share code, notes, and snippets.

@juandelperal
Created August 19, 2020 10:12
Show Gist options
  • Save juandelperal/0028dfb7df2f242e7c9b6756dba915bf to your computer and use it in GitHub Desktop.
Save juandelperal/0028dfb7df2f242e7c9b6756dba915bf to your computer and use it in GitHub Desktop.
JS + CSS vars manipulation
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>JS + CSS vars manipulation</title>
</head>
<style>
body {
background: var(--bg);
}
div {
max-width: 70ch;
padding: 20px;
font-size: calc(1px * var(--fz));
color: var(--color);
}
</style>
<body>
<input type="color"
value="#f3f4f0"
data-cssvar="bg">
<input type="color"
value="#198cbe"
data-cssvar="color">
<input type="range"
value="24"
data-cssvar="fz">
<div>
<h1>Lorem</h1>
<p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Modi omnis eaque, expedita ipsa possimus est rem vitae deleniti ad dicta odio, mollitia dolor, inventore maiores sapiente ut debitis earum sit.</p>
</div>
</body>
<script>
/*
Usage:
<input type="color"
value="10"
value="#555555"
data-target=".myTarget" // <- this is optional
data-cssvar="color">
*/
document.querySelectorAll('[data-cssvar]').forEach(element => {
let cssvarName = '--' + element.dataset.cssvar
let target = document.querySelector(element.dataset.target ?? ':root')
target.style.setProperty(cssvarName, element.value);
element.addEventListener("input", () => {
target.style
.setProperty(cssvarName, element.value);
});
})
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment