[Chartjs]-'filter' function for chart.js legend labels never being called

1👍

Probably should be more a comment than an answer, but I was playing with your fiddle and removed your cdn for chart.js from the fiddle and added the script tag for a cdn (2.8.0) in the HTML. That actually makes the filter function execute and it seems to work that way, although the line connecting the dots in the scatter chart vanishes with that. If you are just using Fiddle to develop you might check that, or check the version of chart.js you are using.

I grabbed one from here: Chart.js CDN’s

I can play the Fiddle a little more and save it just to show you what I am talking about.

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

var config = {
   type: 'scatter',
   data: {
      labels: ["Test","Test","Test"],
      datasets: [{
         label: 'Dataset1',
         type: "scatter",
         borderColor: "red",
         backgroundColor: "red",
         data: [{x: 50, y:10}, {x: 70, y:20}, {x: 80, y:90}],
         fill: false, 
         showLine: true
      }]
   },
   options: {
      responsive: true,
      maintainAspectRatio: false,
      legend : { display: true, position: 'bottom', 
      	labels: {
					filter: function(item, data) {
             // console.log(item.text);
             alert(item.text);
						return false;
          }
        }
      }
   }
}; // end of var config

var myLiveChart = new Chart(ctx, config);
html {
  overflow: hidden;
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js" integrity="sha256-xKeoJ50pzbUGkpQxDYHD7o7hxe0LaOGeguUidbq6vis=" crossorigin="anonymous"></script>
<body style="height: 100%; width: 100%; overflow: hidden; margin: 0;">
<div id="canvas-wrapper" style="height: 100%; width: 100%; overflow-x: scroll; overflow-y: hidden;">
<div id="canvas-holder" style="height: 100%; width: 500px;" oncontextmenu="return false;">
<canvas id="myChart"></canvas>
</div>
</div>
</body>

Put it in a snippet. The weird thing about that is that the filter runs twice even though you have one dataset. Your fiddle is different than your example BTW.

0👍

I realize you need to put filter under labels, not just legend, otherwise it won’t work.

plugins: {
        legend: {
            display:  true,
            position: 'right',
            labels: {
            filter: function(legendItem, data) {
                if (legendItem.index<6) {
                return legendItem}
                //console.log(legendItem.index)

            }},
        }
            //display:  true,
            //position: 'right',
            //font:{size:8},


    }

Leave a comment