How can I add dataset toggle to Chart.js?

0👍

You can just replace the jQuery functions in the question you linked to by their Javascript equivalents.

1.

var ctx = jQuery("#LineChart").get(0).getContext("2d");

becomes

var ctx = document.getElementById("LineChart").getContext("2d");

2.

SPOn = jQuery('.sp').hasClass('enabled');
NCOn = jQuery('.nc').hasClass('enabled');
SPAOn = jQuery('.sp-avg').hasClass('enabled');
NCAOn = jQuery('.nc-avg').hasClass('enabled');

becomes

SPOn = document.getElementsByClassName('sp')[0].className.indexOf('enabled') != -1;
NCOn = document.getElementsByClassName('nc')[0].className.indexOf('enabled') != -1;
SPAOn = document.getElementsByClassName('sp-avg')[0].className.indexOf('enabled') != -1;
NCAOn = document.getElementsByClassName('nc-avg')[0].className.indexOf('enabled') != -1;

3.

jQuery(document).ready(function() {

becomes a javascript block before the end of the tag (there are other ways to do it, but this seemed the easiest to demonstrate)

4.

jQuery('.chart-toggles a').click(function() {

becomes

function toggleLine(t) {

and

<a class="sp enabled" onclick="toggleLine(this)">Toggle SP</a>
<a class="nc enabled" onclick="toggleLine(this)">Toggle NC</a>
<a class="nc-avg enabled" onclick="toggleLine(this)">Toggle NC Avg</a>
<a class="sp-avg enabled" onclick="toggleLine(this)">Toggle SP Avg</a>

5.

jQuery(this).toggleClass('enabled');

becomes

if (t.className.indexOf('enabled') == -1)
     t.className += ' enabled'
else
     t.className = t.className.replace('enabled', '');

Fiddle with no jQuery – http://jsfiddle.net/htc4gyu5/

Notice that I’ve moved everything to the HTML block – that’s mainly for #3 in the above list.

Leave a comment