Search code examples
jqueryhtmlcsscss-variables

Accessing CSS variables via jQuery


How do you get css variables in jquery? I'm trying to replace border: 2px solid #fff with the css variable --border.

Here is my code:

$(".header .navigation").on("show.bs.collapse", function(e) {
  console.log("open")
  $(".navigation").css("border", "2px solid #fff");
});

Solution

  • You can use getComputedStyle method to get all styles and get CSS variable value from it using getPropertyValue method.

    $(".header .navigation").on("show.bs.collapse", function(e) {
      var style = window.getComputedStyle(document.body);
      $(".navigation").css("border", style.getPropertyValue('--border'));
    });
    

    If you want to update the variable via Javascript then you can use setPropertyValue method.

    $(".header .navigation").on("show.bs.collapse", function(e) {
      var style = window.getComputedStyle(document.body);
      style.setPropertyValue('--border', '2px solid #f00');
    });
    

    Or you can use CSS var() for referring a variable through CSS.

    $(".header .navigation").on("show.bs.collapse", function(e) {
      var style = window.getComputedStyle(document.body);
      $(".navigation").css("border", "var(--border)"));
    });