|
| 1 | +<!DOCTYPE html> |
| 2 | +<html lang="en"> |
| 3 | +<head> |
| 4 | + <meta charset="UTF-8"> |
| 5 | + <title>Scoped CSS Variables and JS</title> |
| 6 | +</head> |
| 7 | +<body> |
| 8 | + <h2>Update CSS Variables with <span class='hl'>JS</span></h2> |
| 9 | + |
| 10 | + <div class="controls"> |
| 11 | + <label for="spacing">Spacing:</label> |
| 12 | + <input id="spacing" type="range" name="spacing" min="10" max="200" value="10" data-sizing="px"> |
| 13 | + |
| 14 | + <label for="blur">Blur:</label> |
| 15 | + <input id="blur" type="range" name="blur" min="0" max="25" value="10" data-sizing="px"> |
| 16 | + |
| 17 | + <label for="base">Base Color</label> |
| 18 | + <input id="base" type="color" name="base" value="#ffc600"> |
| 19 | + </div> |
| 20 | + |
| 21 | + <img src="https://source.unsplash.com/7bwQXzbF6KE/800x500"> |
| 22 | + |
| 23 | + <style> |
| 24 | + /* Declare variables in root */ |
| 25 | + :root { |
| 26 | + --base: #ffc600; |
| 27 | + --spacing: 10px; |
| 28 | + --blur: 10px; |
| 29 | + } |
| 30 | + |
| 31 | + img { |
| 32 | + padding: var(--spacing); |
| 33 | + background: var(--base); |
| 34 | + filter: blur(var(--blur)); |
| 35 | + } |
| 36 | + |
| 37 | + .hl { |
| 38 | + color: var(--base); |
| 39 | + } |
| 40 | + |
| 41 | + /* |
| 42 | + misc styles, nothing to do with CSS variables |
| 43 | + */ |
| 44 | + |
| 45 | + body { |
| 46 | + text-align: center; |
| 47 | + background: #193549; |
| 48 | + color: white; |
| 49 | + font-family: 'helvetica neue', sans-serif; |
| 50 | + font-weight: 100; |
| 51 | + font-size: 50px; |
| 52 | + } |
| 53 | + |
| 54 | + .controls { |
| 55 | + margin-bottom: 50px; |
| 56 | + } |
| 57 | + |
| 58 | + input { |
| 59 | + width:100px; |
| 60 | + } |
| 61 | + </style> |
| 62 | + |
| 63 | + <script> |
| 64 | + const inputs = document.querySelectorAll('.controls input'); |
| 65 | + |
| 66 | + //Function that handles input changes |
| 67 | + function handleUpdate() { |
| 68 | + //Print the value of the change |
| 69 | + console.log(this.value); |
| 70 | + //Get suffix from data-sizing or empty for color hex |
| 71 | + const suffix = this.dataset.sizing || ''; |
| 72 | + //Print the suffix of the input |
| 73 | + console.log(suffix); |
| 74 | + //Print the name of the input |
| 75 | + console.log(this.name); |
| 76 | + //Set the property this.name with value (this.value + suffix needed) e.g 10px || #004000 |
| 77 | + document.documentElement.style.setProperty(`--${this.name}`, this.value + suffix); |
| 78 | + } |
| 79 | + |
| 80 | + //Loop through our inputs and listen for changes or mouse movement |
| 81 | + inputs.forEach(input => input.addEventListener('change', handleUpdate)); |
| 82 | + inputs.forEach(input => input.addEventListener('mousemove', handleUpdate)); |
| 83 | + </script> |
| 84 | + |
| 85 | +</body> |
| 86 | +</html> |
0 commit comments