Last active
April 5, 2019 17:36
-
-
Save kevinmmartins/6ba8ccfc035befe7d7822a6d54541577 to your computer and use it in GitHub Desktop.
ChartJS - Show chart data when click
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div style="width: 300px; height: 300px"> | |
<canvas id="myChart"></canvas> | |
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var myNewChart; | |
var data = { | |
datasets: [{ | |
data: [300, 50, 100], | |
backgroundColor: [ | |
"#F7464A", | |
"#46BFBD", | |
"#FDB45C" | |
] | |
}], | |
labels: [ | |
"Red", | |
"Green", | |
"Yellow" | |
] | |
}; | |
$(document).ready( | |
function() { | |
var canvas = document.getElementById("myChart"); | |
var ctx = canvas.getContext("2d"); | |
myNewChart = new Chart(ctx, { | |
type: 'pie', | |
data: data, | |
options: { | |
events: ['mousemove','click'], | |
onClick: graphClickEvent | |
} | |
}); | |
} | |
); | |
function graphClickEvent(event, array){ | |
var activePoints = myNewChart.getElementsAtEvent(event); | |
console.log(activePoints); | |
if (activePoints[0]) { | |
var chartData = activePoints[0]['_chart'].config.data; | |
var idx = activePoints[0]['_index']; | |
var label = chartData.labels[idx]; | |
var value = chartData.datasets[0].data[idx]; | |
var url = "Label=" + label + "\nValue=" + value; | |
console.log(url); | |
alert(url); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment