Chartjs-Chart.js showing old chart on hover

1👍

After you change your data you should update your chart with chartVariable.update().

I made a JSBin which explains you how to use it.

The important function for you is the last in the code, addDataButton() which gets triggered by a button click. In this function I add new data and update my chart after that.

Instead of chartVariable and chart you should use lineChart2 in your case.

Complete code:

let numberOfDataCounter = 0 // Current data counter
const numberOfDataAtBeginning = 4 // data number to start with
const weekdays = ["Su", "Mo", "Du", "We", "Th", "Fr", "Sa"]

function randomNumber(){
  let randomNumber = Math.floor(Math.random()*100)
  return randomNumber
}

let chartData = {
  label: [],
  data: []
}

function addData (){
  chartData.label.push(weekdays[numberOfDataCounter % 7])
  chartData.data.push(randomNumber())

  numberOfDataCounter++
}

// Fill chart with data at beginning
while (numberOfDataAtBeginning>numberOfDataCounter) {
  addData()
}

let data = {
  labels: chartData.label,
  datasets: [{
    label: "Label",
    data: chartData.data
  }]
}

let chart = new Chart(document.getElementById("chart"), {
  type: 'line',
  data: data,  
  options: {
    scales: {
      yAxes: [{
        ticks: {
          min: 0,
          max: 100
        }
      }]
    }
  }
});

function addDataButton(){
  addData()
  chart.update()
}

Leave a comment