The feature to disable legend click in Chart.js does not activate unless the specific condition is met

I am working with chartjs and have encountered a scenario where I need to disable actions when a legend item is clicked, but only under certain conditions. I was able to accomplish this using the following code snippet:

legend: {
    position: 'right',
    onClick: (e) => {
      if (!this.isFilterView)
        e.stopPropagation();
},

However, when the filter view is active, I want the legend items to function as usual when clicked. The current code does not provide this functionality. Is there a way to achieve this?

Answer №1

It seems like your legend.onClick function is overriding the default function, which is why stopping event propagation doesn't work.

The Chart.js documentation provides code snippets in the section "Custom On Click Actions" that mention explicitly invoking the default onClick function to achieve default behavior. Here's how you can modify your code:

var defaultLegendClickHandler = Chart.defaults.global.legend.onClick;
...
legend: {
  position: 'right',
  onClick: (event, legendItem) => {
    if (this.isFilterView) {
      defaultLegendClickHandler(event, legendItem);
    }
  },

However, if this doesn't work, you can manually toggle the hidden state of the datasets based on the value of isFilterView.

legend: {      
  onClick: (event, legendItem) => {
    if (this.isFilterView) {
      myChart.getDatasetMeta(legendItem.datasetIndex).hidden = !legendItem.hidden;
      myChart.update();
    }
  }
},

An example code snippet is provided below that demonstrates how this functionality operates. You can toggle the isFilterView variable using a checkbox at the top left of the canvas.

var isFilterView = false;

var myChart = new Chart('chart', {
  type: 'bar',
  data: {
    labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],
    datasets: [{
        label: 'John Doe',
        data: [1, 2, 3, 4, 5],
        backgroundColor: 'red'
      },
      {
        label: 'Jane Clark',
        data: [5, 4, 3, 2, 1],
        backgroundColor: 'blue'
      },
      {
        label: 'Michael Smith',
        data: [3, 4, 2, 1, 5],
        backgroundColor: 'green'
      }
    ]
  },
  options: {
    legend: {      
      onClick: (event, legendItem) => {
        if (isFilterView) {
          myChart.getDatasetMeta(legendItem.datasetIndex).hidden = !legendItem.hidden;
          myChart.update();
        }
      }
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true,
          stepSize: 1
        }
      }],
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<input id="filterToggle" type="checkbox" onclick='isFilterView = !isFilterView;'>Filter View
<canvas id="chart" height="80"></canvas>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

MongoDB subfield pagination technique

I am looking to retrieve specific data from a sub-field in a MongoDB collection and implement pagination for it. Thank you! { "_id": "616d274c655e0000ee005f32", "subscription": [ { "account_admin&q ...

Error occurs when using Express.js in combination with linting

https://www.youtube.com/watch?v=Fa4cRMaTDUI I am currently following a tutorial and attempting to replicate everything the author is doing. At 19:00 into the video, he sets up a project using vue.js and express.js. He begins by creating a folder named &apo ...

Node's Object.prototype function returns an empty object

When I run Object.prototype in the browser console, I see all the properties and methods within it. However, when I do the same thing in the NodeJS terminal, I get an empty object {}. Can someone explain why this difference occurs? Attached are screenshots ...

What could be causing my jQuery handler to not capture my form submission?

I am developing a Ruby web application and using JQuery and AJAX to send/receive data. However, I am facing an issue where pressing the enter key does not submit the form. What should I do to ensure that my form submits successfully? Within my Foundation ...

Does the useState hook have any connection to hoisting in React?

I am relatively new to React.js and JavaScript, currently working on a project where I need the ability to manually update my components as needed, due to limitations with a third-party library. After doing some research, I came across a pattern on the of ...

Angular Material failing to adapt to mobile devices

My website was created using Angular Material and looks great on desktop, but is completely broken and out of place when viewed on mobile devices. I'm thinking it might be because I haven't set the column size for each element properly. Any advic ...

Pager.js utilizing Deferred Bindings

I am currently working on using Pager.js to develop a single page application. The structure I have set up is as follows: #word/definition #word/example #word/synonym This means that definition, example, and other elements are divs with page bindings: & ...

The error "redux-persist undefined is not an object (evaluating 'action.type')" indicates that there is an issue with the

Struggling with an error in my Redux project using Redux Persist and React Native Looking for help to fix an error in my Redux setup. I am using Redux with React Native and trying to create a store with a reducer. The error I am encount ...

Steps for importing jQuery to vendor.ts in Angular 2 webpack

Currently, I am in the process of setting up my Angular 2 app using webpack. As I review the vendor.ts file, I notice this specific structure. // Angular 2 import '@angular/platform-browser'; import '@angular/platform-browser-dynamic'; ...

What is the optimal order for arranging CSS properties?

Do CSS properties need to be in a specific order? I've always organized them based on my own preference. Is there an official standard for arranging CSS properties? While server-side languages have set standards, it seems like CSS structure is more f ...

Node.js and the concept of handling null values

console.log("variable = " + JSON.stringify(result.something)); After running the code, I see that variable = null However, when I add this condition: if (result.something != null || result.something != '') { console.log('entered' ...

Express Power Tool - Error: app.set function is undefined

My journey with creating an API using Node/Express began with a solo endeavor to learn the basics in a 'naive' manner. The initial setup worked smoothly, prompting me to experiment with express-generator. Upon completion of the setup process, th ...

What is the best method for retrieving the entire row data based on the maximum value in a column?

function findMaxValue() { var highestValue = Math.max.apply(Math, $('.sira').map(function() { return $(this).text() })) alert(highestValue); } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"& ...

Is it possible to verify the data within a VueJS model? It seems that none of the Vue validators are effective

Hello there, It's common knowledge that using Vue-validator with most UI components can be challenging when it comes to validation. I've been utilizing Vue Material Components by @mjanys, which is a fantastic library. The author has included met ...

When setting up Vue.js for unit testing, the default installation may show a message stating that

Recently set up a fresh Vue project on Windows 7 using the VueJS UI utility. Unit testing with Jest enabled and added babel to the mix. However, when running "npm test" in the command line, an error is returned stating 'Error: no test specified' ...

Is there a way to implement personalized error management in TypeScript with Express?

For a while now, I have been using JavaScript to create my APIs but recently made the switch to TypeScript. However, I keep encountering errors along the way. One particular error handler I have set up is for when a route cannot be found, as shown below: i ...

Issues with Angular ngroute: controllers are not functioning properly

In order to route my application with different themes on the same page, I plan to utilize the ngroute module. Here's an example of how I intend to achieve this: <html> <head> <title>Angular JS Views</title> ...

Leveraging $scope variables to dynamically generate new scope values within an Angular controller

I am currently faced with the challenge of using latitude and longitude data provided by the server, which is stored in $scope.Address. I am attempting to create a map object with these values as shown below. However, my current implementation is not fun ...

Combine activities from a dynamic array of Observables

I'm currently utilizing the rxjs library. In my application, I have a Browser object overseeing multiple instances of Page objects. Each page emits a stream of events through an Observable<Event>. Pages can be opened and closed dynamically, le ...

At what point does the browser begin fetching the background images specified in a stylesheet?

Are images mentioned in a valid CSS declaration with a background-image value downloaded when the stylesheet is parsed or when the declaration is applied on a page? In simpler terms, do I need to download all background images listed in my stylesheet even ...