Home > Web Front-end > CSS Tutorial > How to Dynamically Change CSS :root Color Variables with JavaScript?

How to Dynamically Change CSS :root Color Variables with JavaScript?

DDD
Release: 2024-11-24 19:07:11
Original
257 people have browsed it

How to Dynamically Change CSS :root Color Variables with JavaScript?

Changing CSS :root Color Variables in JavaScript

In the realm of web development, customizing the visual aesthetics of a webpage is often accomplished through the use of CSS variables. These variables, defined within the :root section of the CSS, enable developers to control various aspects of the design. One common scenario is the ability to change these colors dynamically using JavaScript.

To achieve this, the key piece of code is:

document.documentElement.style.setProperty('--your-variable', '#YOURCOLOR');
Copy after login

This line essentially modifies the specified CSS variable in the :root section, updating its value to the desired color. For instance, if you want to change the --main-color variable to black, you would use the following code:

document.documentElement.style.setProperty('--main-color', '#000000');
Copy after login

Applying this code to the example provided in the question:

function setTheme(theme) {
  if (theme == 'Dark') {
    localStorage.setItem('panelTheme', theme);
    $('#current-theme').text(theme);
    document.documentElement.style.setProperty('--main-color', '#000000');
  }
  if (theme == 'Blue') {
    localStorage.setItem('panelTheme',  'Blue');
    $('#current-theme').text('Blue');
    alert("Blue");
  }
  if (theme == 'Green') {
    localStorage.setItem('panelTheme', 'Green');
    $('#current-theme').text('Green');
    alert("Green");
  }
}
Copy after login

This updated code successfully modifies the --main-color variable and dynamically changes the colors on the webpage when a button is clicked.

The above is the detailed content of How to Dynamically Change CSS :root Color 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template