09 Jan 2019 | 1 min
Goal: To make the javascript change dynamically the page CSS with the inputs passed through the browser.
See here how is my version of the exercise.
Difference between Wes Bos solution and mine:
Defining the <input> object on Javascript.
Wes defined a constant ‘inputs’ which contains all HTML inputs in a nodeList:
const inputs = document.querySelectorAll('.controls input');
I defined each input as a variable:
let spacing = document.getElementById('spacing');
let blur = document.getElementById('blur');
let base = document.getElementById('base');
Wes defined a ‘suffix’ constant and a ‘nil’ default value, I wrote manually each suffix.
const suffix = this.dataset.sizing || '';
The number of handlers on event listeners.
Wes used two event handlers(change e mousemove) and iterated over the object ‘inputs’:
inputs.forEach(input => input.addEventListener('change', handleUpdate));
inputs.forEach(input => input.addEventListener('mousemove', handleUpdate));
I used one handler(change) for each variable:
spacing.addEventListener("change", updateSpacing);
blur.addEventListener("change", updateBlur);
base.addEventListener("change", updateBase);
(I don’t know why he used the ‘mousemove’ handler if the ‘change’ is enough …)
Fallback function(s) definition.
I defined 3 fallback functions, one for each input:
function updateSpacing() {
image.style.marginTop = `${spacing.value}px`;
image.style.marginLeft = `${spacing.value}px`;
console.log(spacing.value);
}
function updateBlur() {
image.style.filter = `blur(${blur.value}px)`;
console.log(blur.value);
}
function updateBase() {
document.body.style.background = base.value;
console.log(base.value);
}
Wes defined a single fallback function (handleUpdate) for all events and used a JS method that I didn’t know, the setProperty. Here is his update function:
function handleUpdate() {
const suffix = this.dataset.sizing || '';
document.documentElement.style.setProperty(`--${this.name}`, this.value + suffix);
}
Github repositories links: My code, Wes.