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
Release: 2024-12-10 18:35:14
Original
741 people have browsed it

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";
    Copy after login
  • el.style.setProperty:

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

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

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template