Skip to content

Commit ce5b57b

Browse files
committed
CSS Vars totally update defaults from the CSS
1 parent 6f8ea2d commit ce5b57b

1 file changed

Lines changed: 34 additions & 3 deletions

File tree

03 - CSS Variables/index-START.html

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,19 +9,33 @@ <h2>Update CSS Variables with <span class='hl'>JS</span></h2>
99

1010
<div class="controls">
1111
<label for="spacing">Spacing:</label>
12-
<input type="range" name="spacing" min="10" max="200" value="10" data-sizing="px">
12+
<input type="range" name="spacing" min="10" max="200" value="0" data-sizing="px">
1313

1414
<label for="blur">Blur:</label>
15-
<input type="range" name="blur" min="0" max="25" value="10" data-sizing="px">
15+
<input type="range" name="blur" min="0" max="25" value="0" data-sizing="px">
1616

1717
<label for="base">Base Color</label>
18-
<input type="color" name="base" value="#ffc600">
18+
<input type="color" name="base" >
1919
</div>
2020

2121
<img src="https://source.unsplash.com/7bwQXzbF6KE/800x500">
2222

2323
<style>
24+
:root{
25+
--base:#01b8f1;
26+
--spacing: 15px;
27+
--blur: 0px;
28+
}
29+
30+
img{
31+
padding: var(--spacing);
32+
background: var(--base);
33+
filter: blur(var(--blur));
34+
}
2435

36+
.hl{
37+
color: var(--base);
38+
}
2539
/*
2640
misc styles, nothing to do with CSS variables
2741
*/
@@ -53,6 +67,23 @@ <h2>Update CSS Variables with <span class='hl'>JS</span></h2>
5367
</style>
5468

5569
<script>
70+
71+
var computedStyles = window.getComputedStyle(document.documentElement);
72+
function updateValue(prop){
73+
let target = document.querySelector(`input[name='${prop}']`);
74+
const value = computedStyles.getPropertyValue(`--${prop}`).replace("px","");
75+
target.value = value;
76+
}
77+
["base", "spacing", "blur"].forEach(prop => updateValue(prop));
78+
79+
function handleUpdate(){
80+
const suffix = this.dataset.sizing || "";
81+
document.documentElement.style.setProperty(`--${this.name}`, this.value+suffix);
82+
}
83+
84+
const inputs = document.querySelectorAll(".controls input");
85+
inputs.forEach(input => input.addEventListener("input", handleUpdate));
86+
5687
</script>
5788

5889
</body>

0 commit comments

Comments
 (0)