javascript30 — Playing with CSS Variables and JS day3
1 min readOct 7, 2018
#done list
- Array.from
- forEach
- addEventListener — change, mousemove
- css variable — padding: var($ — spacing);
- handle css variable value with javascript
- element.style.setProperty(‘property name’, value)
- :root
#set the CSS variable and update the variable with JS
html {
/* Will be overridden by JS */
--element-height: 20px
}.my-element {
height: var(--element-height);
width: 40px;
color: #9b806b;
}myElement.style.setProperty('--element-height', height + 'px')
#set a new CSS property.
<div id="ex1">Some text.</div>var div = document.getElementById('ex1');
var setprop = div.style.setProperty("background-color", "yellow");
#javascript
const img = document.querySelector('.img');
const inputs = Array.from(document.querySelectorAll('input'));var handleUpdate = function(e){
console.log(this.name)
//img.style.filter = `blur(${this.value}px)`;
if(this.name === "spacing"){
img.style.setProperty('--spacing', this.value + 'px')
}else if (this.name === "blur") {
img.style.setProperty('--blur', this.value + 'px')
}else {
img.style.setProperty('--color', this.value)
}}
inputs.forEach(el => el.addEventListener('change', handleUpdate));
inputs.forEach(el => el.addEventListener('mousemove', handleUpdate));
#reference
https://eager.io/blog/communicating-between-javascript-and-css-with-css-variables/
https://www.smashingmagazine.com/2018/05/css-custom-properties-strategy-guide/
https://medium.com/@_bengarrison/accessing-and-modifying-css-variables-with-javascript-2ccb735bbff0