3

Does jQuery have a way to get and set the value of CSS variables? (MDN - Using CSS variables)

I have tried using the normal css function $(".element").css("--varname", 1), but it doesn't work.

I can use normal DOM functions, but I would prefer not to mix that and jQuery:

element.style.getPropertyValue("--varname");
element.style.setProperty("--varname", value);

I am using this variable in a transform, so getting the result of using the variable gives a matrix3d() string. I need to get the value for some calculations in JS

4
  • 1
    You are missing {}. $('.classname').css({'display': 'block'}); Commented Jul 11, 2016 at 19:24
  • 5
    @Nitin I think he meant literal css variables: developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables Commented Jul 11, 2016 at 19:25
  • 1
    CSS variables aren't associated with specific elements, they're used in the <style> section of the document. Commented Jul 11, 2016 at 19:30
  • @Barmar Not true, CSS variables are set on specific elements and then inherited. Commented Mar 31, 2019 at 12:40

5 Answers 5

2

You can use $.cssHooks, $.support

(function($) {

  // First, check to see if cssHooks are supported
  if (!$.cssHooks) {
    // If not, output an error message
    throw (new Error("jQuery 1.4.3 or above is required"
                     + " for this plugin to work"));
  }

  // Wrap in a document ready call, because jQuery writes
  // cssHooks at this time and will blow away your functions
  // if they exist.
  $(function() {

    $.cssHooks["mainBgColor"] = {
      get: function(elem, computed, extra) {
        // Handle getting the CSS property
        return elem.style.getPropertyValue($.support["mainBgColor"]) 
               || window.getComputedStyle(elem)
                 .getPropertyValue($.support["mainBgColor"])
      },
      set: function(elem, value) {
        // Handle setting the CSS value
        elem.style.setProperty($.support["mainBgColor"], value);
        return elem
      }
    };
    $.support["mainBgColor"] = "--main-bg-color";
    console.log($("h1").css("mainBgColor")); // `"brown"`
    $("h1").css("mainBgColor", "green");
    console.log($("h1").css("mainBgColor")); // `"green"`
  });

})(jQuery);
h1 {
  --main-bg-color: brown;
}
h1 {
  background-color: var(--main-bg-color);
}
<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
  <h1>Hello Plunker!</h1>
  <script>
  </script>
</body>
</html>

plnkr http://plnkr.co/edit/UyhKl8ZpZ9Pyaacl39ay?p=preview

Sign up to request clarification or add additional context in comments.

Comments

1

You're close:

Setter:

$(".element").css("varname", "value");

Getter:

$(".element").css("varname");

For examples:

$(".element").css("display", "none");

Would set the display value to none.

$(".element").css("display");

Would return "none" as the current value of the css property.

Edit for the literal CSS variable Comment:

$(".div").css("background-color", "var(--main-color2)");

Will change the variable of an existing element, so assuming the variables exist you can swap styles around in this manner.

$(".div").css("background-color");

Unfortunately this returned "rgb(255, 0, 0)" for me. It grabbed the RGB that the variable represents. This was tested in Chrome, so your mileage may vary.

2 Comments

display isn't a CSS variable, it's a style name.
Not quite what I'm after, I am using the variable in a transform, so using .css returns a matrix3d() string. I plan to use the value of the variable in a calculation, so I need the value itself.
0

You are declaring an invalid css name. Try using .style attr().

$(".element").attr("style","--varname:1"); // set the value
$(".element").attr("style"); // get the value

Example : https://jsfiddle.net/e6jqa3pn/1/

Comments

0

You can use cssVar (on npm : jq-cssvar), it's a jQuery plugin that gets the job done when it comes to css variables.

(Here is also a link to the github repo).

Comments

0

I've created monkey patch for jQuery css method so with it you can use just:

$(".element").css("--varname", 1);

the patched method call getPropertyValue or setProperty when variable start with two dashes or original method if not (it also handle object as first argument).

https://gist.github.com/jcubic/9ef9fa2561de8430e953e2fe62011c20

I'm providing link since the code may change in gist, if there is bug in it, but I think it's ok since it's pretty simple.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.