forked from wesbos/JavaScript30
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
77 lines (69 loc) · 2.52 KB
/
index.html
File metadata and controls
77 lines (69 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Scoped CSS Variables and JS</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h2>Update CSS Variables with <span class="highlight">JS</span></h2>
<div class="controls">
<div>
<label for="spacing">Spacing: </label>
<div class="input-container">
<input
id="spacing"
type="range"
name="spacing"
min="10"
max="200"
value="10"
data-sizing="px"
/>
</div>
</div>
<div>
<label for="blur">Blur: </label>
<div class="input-container">
<input
id="blur"
type="range"
name="blur"
min="0"
max="25"
value="10"
data-sizing="px"
/>
</div>
</div>
<div>
<label for="base">Base Color: </label>
<div class="input-container">
<input id="base" type="color" name="base" value="#f33f3f" />
</div>
</div>
</div>
<div class="image-block">
<img src="https://source.unsplash.com/7bwQXzbF6KE/800x500" />
</div>
</div>
<script>
const inputs = document.querySelectorAll(".controls input");
inputs.forEach((input) => input.addEventListener("change", handleUpdate));
inputs.forEach((input) =>
input.addEventListener("mousemove", handleUpdate)
);
// This function checks the root element and updates the css variables created on it with the value of the input element, when there's a change or mouve move event. Note that we gave names to the input elements that corresponds with the variable names we set on the root element, hence this.name.
function handleUpdate() {
// To get the "px', assign the data attribute created in the HTML to a variable, then concatenate the string to the input value. This is because the inputs spacing and blur will always be a number but to make it a valid css value, we need to add the unit (px).
// Base Color is already a valid css string value and we'll not need to attach px, hence, the; or empty string (|| " ").
const valueSuffix = this.dataset.sizing || "";
document.documentElement.style.setProperty(
`--${this.name}`,
this.value + `${valueSuffix}`
);
}
</script>
</body>
</html>