Search code examples
javascripthtmlcsscss-variablessetattribute

Why first CSS variable resets when I change second? Custom color theme


The purpose is to make a custom site color theme. The problem is when I changing the second CSS variable first resets to its default value.

enter image description here

enter image description here

var mainColor = document.getElementById("main-color");
var secondColor = document.getElementById("second-color");

function color(cssVariable, inputValue) {
  return cssVariable + ":" + inputValue
}

mainColor.addEventListener('input', function() {
  document.documentElement.setAttribute("style", color("--main-color", this.value))
})

secondColor.addEventListener('input', function() {
  document.documentElement.setAttribute("style", color("--second-color", this.value))
})
:root {
  --main-color: black;
  --second-color: whitesmoke;
  --main-font-size: 16px;
  color: var(--main-color);
  font-size: var(--main-font-size);
}
<div class="dropdown-color-container">
  <input type="color" id="main-color">
  <input type="color" id="second-color">
</div>

Is there any way to save changed CSS variables? And how would you implement code for this, what's the easiest solution? I'm beginner in JS

Runnable code: https://www.w3schools.com/code/tryit.asp?filename=GLDQWOUT9HUA


Solution

  • The issue is that you are setting the style attribute so each time you override all the previous inline style.

    You need to do it differently using setProperty

    var mainColor = document.getElementById("main-color");
    var secondColor = document.getElementById("second-color");
    
    function color(cssVariable, inputValue) {
      return cssVariable + ":" + inputValue
    }
    
    mainColor.addEventListener('input', function() {
      document.documentElement.style.setProperty("--main-color", this.value);
    })
    
    secondColor.addEventListener('input', function() {
      document.documentElement.style.setProperty("--second-color", this.value)
    })
    :root {
      --main-color: black;
      --second-color: whitesmoke;
      --main-font-size: 16px;
      color: var(--main-color);
      font-size: var(--main-font-size);
    }
    <div class="dropdown-color-container">
      <input type="color" id="main-color">
      <input type="color" id="second-color">
    </div>