"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Dynamically Change CSS :root Color Variables with JavaScript?

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

Published on 2024-12-22
Browse:166

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');

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');

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");
  }
}

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

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3