JavaScript30: Day 3 - CSS Variables😲😲🙀
Anik Khan
Posted on July 21, 2020
I've created a project based off of the JavaScript30 Challenge by Wes Bos.
It was about using CSS variables!! I am not sure about you, but I was quite surprised when Wes Bos said that CSS has variables!! I couldn't just wait to try it out.
What So Special About CSS variables?
CSS variables are not like SASS variables. You can change the CSS variables value from HTML via JavaScript DOM manipulation. How cool is that!💗
What the project about?
It is to create some input control for blur effect, padding, and changing the background on an image.
Lesson
- My main lesson was to try the CSS variables and changing their values using DOM manipulation.
- CSS variables should be declared at the root with --
/*these are the css variables*/
:root {
--space: 10px;
--blur: 0px;
--color: #fa8072;
}
- We assign them like-
img {
background: var(--color);
padding: var(--space);
filter: blur(var(--blur));
}
- Also got a chance to know more about the template string. I was stuck for a while because of this-
//create property and set value accordingly
document.documentElement.style.setProperty(`${--this.name}`, this.value + unit);
//`${--this.name}` is so wrong. I thought it would give me output like: --space
//correct way: `--${this.name}`
Live URL
There you go: http://blur-it.surge.sh/
Code
Here's the Js code, plz refer to GitHub for full code-
//changeTheImage method
const changeTheImage = function () {
//get the unit
const unit = this.dataset.sizing || ``;
//create property and set value accordingly
document.documentElement.style.setProperty(`--${this.name}`, this.value + unit);
/********PERSONAL EXPERIMENT*********/
//console.log(`--${this.name}`) //this is correct
//console.log(typeof `--${this.name}`) //string
//console.log(typeof this.value) //string
// console.log(--this.name) //this is wrong
// console.log(--`${this.name}`) //this is wrong
/*************************************/
}
//select all the inputs
const inputs = document.querySelectorAll('input');
//addEventlistener to each of the input to detect change
inputs.forEach((input) => input.addEventListener('change', changeTheImage));
inputs.forEach((input) => input.addEventListener('mousemove', changeTheImage));
GitHub
💖 💪 🙅 🚩
Anik Khan
Posted on July 21, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.