Reputation:
Here is my chart creation
createChart = function (name, contributions, idArray) {
globalIdArray = idArray;
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: "bar",
data: {
labels: name,
datasets: [{
label: "Contributions",
data: contributions,
backgroundColor: [
'rgba(0, 255, 0, 0.2)',
'rgba(0, 255, 0, 0.2)',
'rgba(0, 255, 0, 0.2)',
'rgba(0, 255, 0, 0.2)',
'rgba(0, 255, 0, 0.2)'
]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
onClick: handleClick,
onHover: handleHover
}
});
This is the HTML, everything is JavaScript and resides inside the canvas element.
<canvas chart-hover="onHover" id="myChart" width="200" height="200"></canvas>
I made it so when I click on a bar they act as a "drill in" and take my a page with more details. To do that I used this code:
function handleClick(e) {
debugger;
var activeElement = myChart.getElementAtEvent(e);
var designerId = _idArray[activeElement[0]._index];
window.location.href = "/Display/search/index?designerId=" + designerId;
}
I'd like to make it so my cursor changes to a pointer to let the user know they can click the bar (as it would normally change with a link). I saw some examples of this on Stack Overflow but they were from the last year or two, the posts included comments asking for an updated version but no solutions.
Here is another post I saw which I believe is the same thing I am trying to accomplish but it didn't work for me.
How to change cursor style to pointer on hovering over points of the chart?
Does anyone know of how I can implement this, using the most recent live version of ChartJS?
Upvotes: 6
Views: 3796
Reputation: 116
To change the cursor to a pointer when hovering over items in a Chart.js
chart, you can use the onHover
option like this:
const ctx = document.getElementById('myChart');
new Chart(ctx, {
type: 'bar',
data: {
labels: ['First', 'Second', 'Third'],
datasets: [{
label: 'Sales',
data: [10, 20, 30],
borderWidth: 1
}]
},
options: {
onHover: (event, chartElement) => {
if (chartElement.length) {
event.native.target.style.cursor = 'pointer';
} else {
event.native.target.style.cursor = 'default';
}
}
}
});
Upvotes: 0
Reputation: 8670
there is a cursor property in css that you can set. for example :
span.crosshair {
cursor: crosshair;
}
span.help {
cursor: help;
}
span.wait {
cursor: wait;
}
Please refer to this link for more information
Upvotes: 1
Reputation: 403
I needed the cursor to change only when over a bar or point on a line chart so came up with this simple solution. Place your function outside the chart declaration.
var chart = new Chart(ctx, {
data: {...},
options: {
onHover: graphHover
}
});
function graphHover(e, array) {
if(array.length > 0) {
e.target.style.cursor = 'pointer';
}else {
e.target.style.cursor = '';
}
}
Upvotes: 5