I want add a unique url to each bar and open that url on click one of bar. But in my case i have two datasets. I am using onClick event which return active record of both dataset.
I am using following code.. It will return both dataset object...it should return only one dataset.
<script>
var barChartData = {
labels: ["Jan","Feb","March"],
datasets: [{
label : "Quoted",
backgroundColor : "#FF7228",
data : [50,20,70],
},
{
label : "Accepted",
backgroundColor : "#FFCC8C",
data : [30,10,20],
},
]
};
window.onload = function() {
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
events:['click'],
onClick:function(c,i){
console.log(this.active);
}
},
responsive: true,
legend: {
position: 'top',
},
}
});
};
</script>
clear() Will clear the chart canvas.
js convention is to call it ctx . An object literal containing the data and the configuration options that Chart. js will use to build your chart. The required properties are type and data . In our example type is 'line' because we want a line chart.
For Chart. js you do this by adding a canvas element, and setting width and height to define the proportions of your graph.
You can use getElementAtEvent()
method to get only one dataset returned. Then you can apply further logic to detect which bar is clicked on.
ᴅᴇᴍᴏ
var barChartData = {
labels: ["Jan", "Feb", "March"],
datasets: [{
label: "Quoted",
backgroundColor: "#FF7228",
data: [50, 20, 70],
}, {
label: "Accepted",
backgroundColor: "#FFCC8C",
data: [30, 10, 20],
}]
};
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
onClick: function(e) {
var bar = this.getElementAtEvent(e)[0];
var index = bar._index;
var datasetIndex = bar._datasetIndex;
// check which bar is clicked
if (index == 0 && datasetIndex == 0) alert('First BAR Clicked!');
else if (index == 0 && datasetIndex == 1) alert('Second BAR Clicked!');
else if (index == 1 && datasetIndex == 0) alert('Third BAR Clicked!');
else if (index == 1 && datasetIndex == 1) alert('Fourth BAR Clicked!');
else if (index == 2 && datasetIndex == 0) alert('Fifth BAR Clicked!');
else if (index == 2 && datasetIndex == 1) alert('Sixth BAR Clicked!');
}
},
responsive: true,
legend: {
position: 'top',
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="canvas"></canvas>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With