Home >Web Front-end >CSS Tutorial >How Can I Programmatically Change CSS Variables with JavaScript?

How Can I Programmatically Change CSS Variables with JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-12-10 18:35:14686browse

How Can I Programmatically Change CSS Variables with JavaScript?

Changing CSS Variables with JavaScript

Controlling the colors of a project through CSS variables allows for easy theming. However, setting these variables programmatically can be challenging.

Initially, attempts were made to modify the attribute using setAttribute and jQuery's .css method. However, these resulted in errors.

Solution:

CSS variables can be edited using one of these three methods:

  • el.style.cssText:

    document.documentElement.style.cssText = "--main-background-color: red";
  • el.style.setProperty:

    document.documentElement.style.setProperty("--main-background-color", "green");
  • el.setAttribute:

    document.documentElement.setAttribute("style", "--main-background-color: green");

The last method was the one used initially but with an incorrect syntax.

Demo:

This demo demonstrates a CSS variable that defines a background color, which is changed by JavaScript after 2 seconds:

<html>
<head>
  <style>
    html {
      --main-background-image: url(../images/starsBackground.jpg);
      --main-text-color: #4CAF50;
      --main-background-color: rgba(0,0,0,.25);
      --beta-background-color: rgba(0,0,0,.85);
    }

    body {
      background-color: var(--main-background-color);
    }
  </style>
</head>
<body onload="setTimeout(function() {
    document.documentElement.style.cssText = '--main-background-color: red';
  }, 2000);">
</body>
</html>

The above is the detailed content of How Can I Programmatically Change CSS Variables with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn