monsoonrainbow
monsoonrainbow

Reputation: 159

Immediate selection of same slice of google pie chart not recognised

I am trying to display a modal with certain infomation when a particular slice of google pie chart is selected. The code is working fine when different slices are selected one after another but event is not being fired when same slice is selected for consecutively for the 2nd time.

google.visualization.events.addListener(chart, 'select', selectHandler);
function selectHandler()
                    {
                        var selectedItem = chart.getSelection()[0];
                        if (selectedItem)
                        {
                            alert("here");
                        }
                    }

Upvotes: 3

Views: 375

Answers (1)

WhiteHat
WhiteHat

Reputation: 61275

the event is fired but the second time a slice is clicked, it is un-selected.

you should check the length of the selection before trying to access --> [0]

see following example...

google.charts.load('current', {
  callback: function () {
    var data = google.visualization.arrayToDataTable([
      ['Task', 'Hours per Day'],
      ['Work',     12],
      ['Eat',       2],
      ['Drink',     1],
      ['Commute',   1],
      ['Surf',      1],
      ['Watch TV',  1],
      ['Sleep',     6]
    ]);

    var pieChart = new google.visualization.PieChart(document.getElementById('piechart'));
    google.visualization.events.addListener(pieChart, 'select', function () {
      document.getElementById('selection').innerHTML = 'Items selected: ' + pieChart.getSelection().length;
    });
    pieChart.draw(data, {});
  },
  packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="piechart"></div>
<div id="selection"></div>

Upvotes: 3

Related Questions