30 Jul 2020


Given a starter page with an image and three controls:

These respectively change the padding around the image, the amount of blur applied to the image, and the color background of the padding (as well as part of the title).


The general strategy is to use CSS variables and JS to update these CSS variables from the inputs.

The CSS variables are defined on the root, making them globally available. The respective elements are then styled as usual in CSS, however the values are set to their respective CSS variable.

Then querySelectorAll to build a nodeList of all the controls on the page, in this case by selecting the parent div by class and selecting all inputs inside.

Using this nodeList, forEach is used to apply eventListeners to all elements listening for the “change” event. Additional eventListeners can be added to listen for “mousemove” event which will allow the JS to run as the sliders are being dragged without releasing the mouse button.

These eventListeners function grabs the document.documentElement and directly sets the document.documentElement.style.setProperty to access the CSS variables. These are then set based on the input using a backtick string, which conveniently take the input name, value, as well as the suffix (necessary for padding in pixels). The last is conveniently stored inside a “data” attribute in the input tag, and is also accessed from the .dataset property of the input.

Things Learned