Search code examples
javascriptjquerycsscss-variables

Modify CSS variables / custom properties in jQuery


In my application, I've got some parameters that I wanted to put in CSS variables using jQuery. And I wanted to read them too.

I was having trouble to read the values back of the CSS variables and tried many things… before I found a solution in the “Questions that may already have your answer” while I was typing my question.

Anyway, I attached a snippet, because I need to know:
⋅⋅⋅ Why the method 1 isn't working ?
⋅⋅⋅ Is there a way to get the CSS var value using jQuery ?

I feel like it lacks an easy solution to handle CSS vars… Am I wrong ?
Of course I'll use the javascript solution if there isn't any way. But I'd like to be sure about it.
Thanks in advance for any answer.

// This method doesn't work for writing CSS var.
$(":root").css("--color1", "red");
console.log(".css method on “:root”      :", $(":root").css("--color1"));

// This methods works for writing CSS var:
$(":root")[0].style.setProperty("--color2", "lime");
console.log("[0].style method on “:root” :", $(":root")[0].style.getPropertyValue('--color2'));
#p1 {
  background-color: var(--color1);
}

#p2 {
  background-color: var(--color2);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>

<body id="bodyID">
  <p id="p1">p with background --color1</p>
  <p id="p2">p with background --color2</p>
</body>

<html>


Solution

  • jQuery only supports CSS custom properties in version 3.2.0 and later. There is no support for them in 2.x or earlier, so accessing them with .css() will not work in those versions. If upgrading jQuery is not an option, you will need to use the built-in style object to access them.

    $(":root").css("--color1", "red");
    console.log(".css method on “:root”      :", $(":root").css("--color1"));
    
    $(":root")[0].style.setProperty("--color2", "lime");
    console.log("[0].style method on “:root” :", $(":root")[0].style.getPropertyValue('--color2'));
    #p1 {
      background-color: var(--color1);
    }
    
    #p2 {
      background-color: var(--color2);
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
    <p id="p1">p with background --color1</p>
    <p id="p2">p with background --color2</p>