loading...
Cover image for JavaScript30: Day 3 - CSS Variables😲😲🙀

JavaScript30: Day 3 - CSS Variables😲😲🙀

akdeberg profile image Anik Khan ・2 min read

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/

Alt Text

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

View on GitHub

Posted on by:

akdeberg profile

Anik Khan

@akdeberg

Convincing computers to do human tasks

Discussion

pic
Editor guide
 

Thanks for this article. I didn't have any idea there were variables in CSS too. Looks like they've been out and are well documented

 

Yeah, it caught me surprise that I didn't know about such a nice thing. And special thanks for the documentation links. It'll be mine go-to resource😉