[Chartjs]-Highlight date in Chart.js line graph

1👍

You can access the chart instance itself on which the labels live, changing your function to this will let you access the dates:

function customRadius(context) {
  let index = context.dataIndex;
  let value = context.dataset.data[index];
  const label = context.chart.data.labels[index]
  console.log(label)
  return index === 300 || value >= 1000000 ?
    10 :
    2;
}

Live sample:

const but = document.getElementById('myButton');

function customRadius(context) {
  let index = context.dataIndex;
  let value = context.dataset.data[index];
  const label = context.chart.data.labels[index]
  // console.log(label)
  return label === '2020-11-17' ?
    10 :
    2;
}

but.addEventListener('click', function() {
  let dates = [];
  let confirmed = [];
  let recovered = [];
  let deaths = [];

  fetch("https://pomber.github.io/covid19/timeseries.json")
    .then(response => response.json())
    .then(data => {
      data["South Africa"].forEach(o => {
        dates.push(o.date);
        confirmed.push(o.confirmed);
        recovered.push(o.recovered);
        deaths.push(o.deaths);
      })
      new Chart(document.getElementById('myChart'), {
        type: 'line',
        data: {
          labels: dates,
          datasets: [{
              label: 'Confirmed',
              borderColor: 'orange',
              backgroundColor: 'orange',
              fill: 'false',
              data: confirmed
            },
            {
              label: 'Recovered',
              borderColor: 'green',
              backgroundColor: 'green',
              fill: 'false',
              data: recovered
            },
            {
              label: 'Deaths',
              borderColor: 'red',
              backgroundColor: 'red',
              fill: 'false',
              data: deaths
            }
          ]
        },
        options: {
          responsive: true,
          animation: {
            duration: 0
          },
          elements: {
            point: {
              radius: customRadius,
              display: true
            }
          },
          title: {
            display: true,
            text: 'Covid-19 / South Africa'
          }
        }
      });
    });

});
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
</head>

<body>
  <button type="button" id="myButton">Click me</button>

  <canvas id="myChart" height="100"></canvas>
</body>

</html>

Leave a comment