2

I would like to change the color of the label on-hovering over the data bar in chartJS. But the color change is not responsive. Below shows the onhover code that I am using. Does anyone have any ideas how to change the color of the label on-hover?

var chart = new Chart(ctx, {
type: 'horizontalBar',
   data: {
      labels: ["Label 1", "Label 2", "Label 3", "Label 4", "Label 5", "Label 6", "Label 7"],
      datasets: [{
         data: [2000, 4000, 6000, 8000, 10000, 12000, 14000],
         backgroundColor: ["#73BFB8", "#73BFB8", "#73BFB8", "#73BFB8", "#73BFB8", "#73BFB8", "#73BFB8"], 
      }]
   },
   options: {
        responsive: true,
        legend: {
            display: false,
        },
        scales: {
            yAxes: [{
                gridLines: {
                    display: true,
                    drawTicks: true,
                    drawOnChartArea: false
            },    
            }],
            xAxes: [{
                gridLines: {
                    display: true,
                    drawTicks: false,
                    tickMarkLength: 5,
                    drawBorder: false
                },  
            }]
        },
        onHover: function (e, item) {
            if (item.length > 0) {
                var i = item[0]._index;
                var $ctx = item[0]._chart.ctx;
                var label = item[0]._chart.config.data.labels[i];
                var data = item[0]._chart.config.data.datasets[0]._meta[0].data[i];
                var startOfBarGraph = data._xScale.left;
                var offset = 9;
                var textWidth = $ctx.measureText(label).width;
                var x = startOfBarGraph - offset - textWidth - 3;
                var y = data._model.y;
                var fontHeight = $ctx.measureText(label).actualBoundingBoxAscent + $ctx.measureText(label).actualBoundingBoxDescent;

                $ctx.fillStyle = 'white';
                $ctx.fillRect(x, y + 3 - fontHeight, textWidth, fontHeight + 4);
                $ctx.fillStyle = 'red';
                $ctx.font = "12px Arial";
                $ctx.fillText(label, x, y + 3);
                
                console.log("onHover", item, e.type);
            }
        }
    }
});

I would like the axis label to look similar to the image below enter image description here

ivor
  • 49
  • 2
  • 5

1 Answers1

0

inside of your dataset datasets: [{ data: [2000, 4000, 6000, 8000, 10000, 12000, 14000], backgroundColor: ["#73BFB8", "#73BFB8", "#73BFB8", "#73BFB8", "#73BFB8", "#73BFB8", "#73BFB8"], }]

try adding hoverBackgroundColor:

Blondish
  • 141
  • 1
  • 9
  • Thanks for your response but unfortunately, that does not change the color of the label text. I was hoping to change the label text color as you hover over the bars. If you wiggle the mouse on the bar, it does change the color of the label text. But I wanted be more responsive and change the color of the text instantly on hovering. – ivor Apr 07 '21 at 12:37