JS30 Challenge Day 03 — CSS Variables
Here we have a unique challenge this time around with an image that updates in realtime when you modify the options above. The options provided for you changes their respective CSS property with JavaScript using AddEventListener
. What actually happens is we create variables and declare them in the highest element the :root
pseudo-class which sets all changes throughout the page as it has a global scope.
If we wish to use one of variables we start with var(--variable_name)
. CSS variables are declared with a --
prefix. Custom CSS variables do inherit from their parent! So if one of the custom variables has no value set, it will inherit the property from it’s parent.
Note: Custom CSS variables are case-sensitive! --my-color
is considered a separate variable to --My-color
.
After setting up your custom variables, we need to write some JavaScript to update our inputs. By placing all your inputs in one <div>
tag, we will be able to make our changes at once. For clear naming convention, we shall name our <div>
tag containing our inputs controls
. So let’s setup a variable that selects all our inputs within our controls
class.
We declare a variable that queries all our specified selectors within our document, so it would look for tags with controls class name that have input tags. Another thing you might have noticed is when you attempt to change your inputs. We have pixels for our spacing, blur, radius with px
and the values shown in inputs if you console.log them are integers only. So to get them to have that additional info we add a custom data attribute in our input tags. You can learn more about custom data attributes here.
After adding an event listener for your inputs, we will implement a function when the specified event occurs. This is where handleUpdate()
comes into play. We declare a variable that refers to the dataset we defined in our input tags. However, we have a problem if we refer only to our dataset since our color input does not have one so it will be undefined when appended, so we add the OR operator to append nothing if there is no dataset.
Now with that complete, we update the our variables by selecting the whole document and setting the property through the name we label in our input tags and with that our challenge should be complete. Dragging our inputs should update our variables appropriately. The repo can be found here and a demo can be found here.