Skip to content
Advertisement

JavaScript function based on counter

I have a chartJS graph. What I am trying to do is to enlarge the section of my graph when a segment of the pie chart is selected. Then decrease it when another section is selected. I am able to increase the section by the following (this works):

onClick: (evt, item) => {
    item[0].element.outerRadius += 10;
},

if you imagine a pie chart I want to select a segment and enlarge it, then when I select a different segment I want the original segmentto shrink and increase the size of the newly selected segment. I am trying to use a counter that toggles between 1 and 0 and enlarge / decrease the size of the segment depending on the counter value: So the below code works, but only if I click on the same section twice. the first time I click the segment it will enlarge, and the second time I click the same segment it will decrease in size.

The problem is that when I select one segment it enlarges and then when I click another segment it decreases the second segment. How can I fix this?

Var global_enlarging_toggle = 0;

onClick: (evt, item) => {

    if (global_enlarging_toggle == 0){
        global_enlarging_toggle = 1;
        item[0].element.outerRadius += 10;
    } else {
        item[0].element.outerRadius -= 10;
        global_enlarging_toggle = 0;
    }

    console.log(global_enlarging_toggle)
    console.log(item[0].element.outerRadius);
}

,

What ive been trying:

Ive been trying to somehow utilise what was clicked first and what was clicked second and if they and check if they are the same or not. but i cant figure it out. I have done this by setting 2 new variables:

var first_segment;
var second_segment;




onClick: (evt, item) => {
    
        if (global_enlarging_toggle == 0){
            global_enlarging_toggle = 1;
            item[0].element.outerRadius += 10;
            first_segment = chart.data.labels[activeEls[0].index];
        } else if (first_segment != second_segment) {
            item[0].element.outerRadius -= 10;
            global_enlarging_toggle = 0;
            second_segment = first_segment;
        }
    
        console.log(global_enlarging_toggle)
        console.log(item[0].element.outerRadius);
    }

But it doesnt work

Advertisement

Answer

This is because you have a singel global toggle. If you instead make an object where you track each element of they have been clicked and thus expanded you wont have this behaviour:

const enlarged = {};
const expandAmount = 10;

const options = {
  type: 'pie',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
    }]
  },
  options: {
    onClick: (evt, activeEls, chart) => {
      const key = `${activeEls[0].datasetIndex}${activeEls[0].index}`;

      if (enlarged[key] || enlarged[key] === undefined) {
        activeEls[0].element.outerRadius += expandAmount;
        enlarged[key] = false;
      } else {
        activeEls[0].element.outerRadius -= expandAmount;
        enlarged[key] = true;
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.1/chart.js"></script>
</body>

EDIT:

Update with desired behaviour, keep a global variable that keeps track of the current dataset and data index, if set first set that back and then enlarge the current slice, if key is same as old key dont do anything

let enlarged = '';
const expandAmount = 10;

const options = {
  type: 'pie',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
    }]
  },
  options: {
    onClick: (evt, activeEls, chart) => {
      const key = `${activeEls[0].datasetIndex}-${activeEls[0].index}`;
      const keys = enlarged.split('-');

      if (keys.length == 2) {
        chart.getDatasetMeta(keys[0]).data[keys[1]].outerRadius -= expandAmount
      }

      if (key !== enlarged) {
        activeEls[0].element.outerRadius += expandAmount;
        enlarged = key;
      } else {
        enlarged = ''
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.1/chart.js"></script>
</body>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement