change css variable with javascript

Changing CSS Variables with JavaScript

As a web developer, I have come across situations where I needed to change CSS variables dynamically using JavaScript. For instance, I had to implement a feature where the background color of a page changes depending on the time of day. To do this, I used JavaScript to change the value of a CSS variable.

Method 1: Using document.documentElement.style.setProperty()

The first and simplest way to change a CSS variable using JavaScript is by using the setProperty() method. This method allows you to change any CSS property, including variables.

Here's an example:

:root {
  --background-color: #fff;
}

body {
  background-color: var(--background-color);
}

To change the value of the --background-color variable using JavaScript, you can use the following code:

document.documentElement.style.setProperty('--background-color', '#000');

This sets the value of the --background-color variable to #000, which is black.

Method 2: Using CSSStyleSheet.insertRule()

Another way to change a CSS variable using JavaScript is by using the insertRule() method of the CSSStyleSheet interface. This method allows you to add or modify a CSS rule dynamically.

Here's an example:

:root {
  --background-color: #fff;
}

body {
  background-color: var(--background-color);
}

To change the value of the --background-color variable using JavaScript, you can use the following code:

const sheet = window.document.styleSheets[0];
sheet.insertRule(':root {--background-color: #000;}', sheet.cssRules.length);

This adds a new CSS rule that sets the value of the --background-color variable to #000, which is black.

Conclusion

In conclusion, there are different ways to change CSS variables using JavaScript. The setProperty() method is the simplest and most straightforward method, while the insertRule() method provides more flexibility and control over the CSS rules. It's important to choose the method that suits your specific use case and preferences.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe