HomeJavascriptHow To Change CSS Variable With Javascript

How To Change CSS Variable With Javascript

Hey everyone. Welcome to today’s tutorial. In today’s tutorial, we will learn how to change CSS variable with Javascript.

This is going to be a quick tutorial. If you would like to improve your HTML, CSS or Javascript knowledge through quick tutorials like this one you can check out this playlist here. This playlist consists of a bunch of quick tutorials based on HTML, CSS and Javascript that will help you improve your skills.

Video Tutorial:

If you prefer to learn by watching a video tutorial rather than reading a blog post you can check out the video down below. Also, subscribe to my youtube channel, where I post new tutorials every alternate day.

Project Folder Structure:

Before we start coding, let us create the project folder structure. We create a project folder called – ‘Change CSS Variable’. Inside this folder, we have just one file – index.html. This is the HTML document. If you want to include an external stylesheet or script file, you can go ahead and do so.

HTML:

Here the HTML code consists of no tags or anything.

CSS:

Now coming to CSS, we start by creating a variable by declaring it in the ‘: root’ selector. The ‘: root’ selector targets the document’s root element. The variable declared in ‘: root’ is the global scope.
Now copy the code provided to you below and paste it into your stylesheet.

:root {
    --bg-color: #5372ef;
}
body {
    background-color: var(--bg-color);
}

Javascript:

Next, we add functionality to this code using Javascript. Once again, copy the code below and paste it into your script file.

To change this variable with javascript, we target the HTML element and set it to the value of our choice.

document.documentElement.style.cssText = "--bg-color: rgb(120,60,23)";

That’s it for this tutorial. If you face any issues while creating this code you can download the source code by clicking on the ‘Download Code’ button below. Also, I would love to hear from you guys. So if you have any queries, feedback or suggestions you can comment below.
Happy Coding!

Previous articleMCQ – 1/10/22
Next articleMCQ – 3/10/22
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

2 × 4 =

Most Popular