简体   繁体   中英

Capture event when user clicks on x axis on Google charts

I am using Angular Google Charts . I am working on a requirement where I need to change the format of x axis values when user clicks on them. Like absolute value <=> Percentage Value. Is there any way I can capture the event when user clicks anywhere on x axis and not other parts of chart?

I tried angular's (click) event however It is not giving me any information as which part of the chart is clicked.

depends on the chart being used,
most charts in the 'corechart' package have a 'click' event.
check the events section in the docs for the particular chart.

the 'click' event will receive an argument with a targetID of the chart element clicked.
when a x-axis label is clicked, the targetID will have the following form.

hAxis#0#label#0

where the first 0 is the index of the axis (always zero when there is only one x-axis)
and the second 0 is the index of the label clicked.

so the following would indicate the second x-axis label, on the first x-axis, was clicked.

hAxis#0#label#1

as such, we can use a regex expression to determine if any x-axis label was clicked.

/hAxis#(\d+)#label#(\d+)/

see following working snippet,
click the chart to see the result.

 google.charts.load('current', { packages: ['corechart'] }).then(function () { var data = new google.visualization.DataTable(); data.addColumn('number', 'x'); data.addColumn('number', 'y0'); for (var i = 0; i <= 100; i++) { var direction = (i % 2 === 0) ? 1 : -1; data.addRow([i, (2 * i * direction)]); } var options = { curveType: 'function' }; var chart = new google.visualization.LineChart(document.getElementById('chart_div')); google.visualization.events.addListener(chart, 'click', function(e) { var match = e.targetID.match(/hAxis#(\\d+)#label#(\\d+)/); if ((match !== null) && (match.length > 0)) { console.log('x-axis label -->', e.targetID); } else { console.log('not x-axis label -->', e.targetID); } }); chart.draw(data, options); }); 
 <script src="https://www.gstatic.com/charts/loader.js"></script> <div id="chart_div"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM