Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using CSS variables (color) with chart.js - "var(--primaryColor)" not working

Tags:

chart.js

I've got a web-app project that uses two stylesheets to define two color sets (day & night mode). Each stylesheet defines the same CSS variables with different colors (e.g. "--primaryColor: 'white'" in dayMode.css and "--primaryColor: 'black'" in nightMode.css. The stylesheet is toggled when clicking a button.

Now, all elements are colored by referring to these variables - both in the CSS and JS code. For example:

div {background-color: var(--primaryColor);}

$(this).css({backgroundColor: "var(--primaryColor)"});

When switching the stylesheet, all elements adjust to the new definitions. Now I set up my very first Chart.js and tried to color it with my variables, like:

yAxes: [{
    ticks: {
        fontColor: "var(--primaryTextColor)"
    }
}]

But that doesn't work. Any idea how to fix this? Thanks in advance!

like image 996
Jacob Stahl Avatar asked Mar 10 '18 11:03

Jacob Stahl


People also ask

What is var (-- in CSS?

The var() CSS function can be used to insert the value of a custom property (sometimes called a "CSS variable") instead of any part of a value of another property.

Can I use CSS variables in JavaScript?

CSS variables have access to the DOM, which means that you can change them with JavaScript.


1 Answers

CSS variables are used in stylesheet, if you would access them in JS you can do like below snippet:

var style = getComputedStyle(document.body);
var primCol = style.getPropertyValue('--primaryColor');
$("#mydiv").text("primaryColor: " + primCol);
:root {
  --primaryColor: #336699;
}

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

</div>

So in a chart.js:

var style = getComputedStyle(document.body);
var primCol = style.getPropertyValue('--primaryColor');
var chartCol = style.getPropertyValue('--chartColor');

var chartData = {
  labels: ['a', 'b', 'c', 'd'],
  datasets: [{
    label: 'value',
    backgroundColor: 'rgba(219, 20, 0, 0.2)',
    borderColor: chartCol,
    data: [30, 50, 25, 10]
  }]
};

var ctx = document.getElementById("myChart").getContext("2d");
var myBar = new Chart(ctx, {
  type: 'line',
  data: chartData,
  options: {
  	legend: { display: false },
    scales: {    
      yAxes: [{
        ticks: {
          fontColor: primCol,
        }
      }],
      xAxes: [{
        ticks: {
          beginAtZero: true
        }
      }],
    }
  }
});
:root {
  --primaryColor: #00ff00;
  --chartColor: #ff0000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="myChart" height="300" width="500"></canvas>
like image 116
beaver Avatar answered Oct 09 '22 03:10

beaver