Skip to content

Instantly share code, notes, and snippets.

@MichaelNahum
Last active January 21, 2017 18:12
Show Gist options
  • Save MichaelNahum/4bd40a0572ec1a4578fe06fc1dc8540c to your computer and use it in GitHub Desktop.
Save MichaelNahum/4bd40a0572ec1a4578fe06fc1dc8540c to your computer and use it in GitHub Desktop.
JSDay30.3
CSS variables normally declared on an element. In this lesson, they're declared on :root "which is similar to declaring them
on an html element".
<style>
:root {
--base: #ffc600;
--spacing: 10px;
--blur: 10px;
}
</style>
Once declared, we can start using them. So, within <style>
img {
padding: var(--spacing);
background: var(--base);
filter: blur(var(--blur));
}
.hl {
color: var(--base);
}
Now for the JS logic. Within the <script> tags:
const inputs = document.querySelectorAll('.controls input');
function handleUpdate() {
const suffix = this.dataset.sizing || ''; //dataset is an object that will contain all the data attributes from that element.
//Two inputs (spacing and blur) have a 'data-sizing' attribute of 'px', because they are manipulated in increments of px.
//However, the third input (base) has no px suffix. Hence the 'or nothing' option of || ''
document.documentElement.style.setProperty(`--${this.name}`, this.value + suffix);
}
//The first half of line 32 grabs the element we want to manipulate. The second half interpolates the element being clicked, and resets its value to whatever the user gives it.
//The "+ suffix" ensures that the elements are manipulated in the correct increment.
inputs.forEach(input => input.addEventListener('change', handleUpdate)) //executes the handleUpdate function when the color is changed.
inputs.forEach(input => input.addEventListener('mousemove', handleUpdate)) //executes the handleUpdate function when the blur or padding inputs are clicked-and-dragged
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment