Chartjs-Chartjs to show more set of data of click of a button

1👍

Here’s my solution. You keep all your data in your variables and show only a few of you data at the start. When you click the button you change the displayed data.
I always keep my data and options in seperate variables for an easier access.

Important Code (without options, colors and comments) (complete code with live preview here (JSBin)):

var campSourceLabels = ["Facebook", "Google", "Landing \nPage", "Email \nCampaign", "Alt landing \npage", "Forum \nLink"];
var campSourceDataTv = [64, 66, 99, 76, 59, 76];
var campSourceDataTl = [36, 53, 76, 70, 55, 89];
var campSourceDataCr = [47, 47, 69, 47, 47, 47];
var displayCount = 4

function showAllData() {
  chartData.labels = campSourceLabels
  chartData.datasets[0].data = campSourceDataTv
  chartData.datasets[1].data = campSourceDataTl
  chartData.datasets[2].data = campSourceDataCr
  chart2.update()
}

var chartData = {
  labels: campSourceLabels.slice(0, displayCount),
  datasets: [{
    label: 'Total Visitors',
    data: campSourceDataTv.slice(0, displayCount)
  }, {
    label: 'Total Leads',
    data: campSourceDataTl.slice(0, displayCount)
  }, {
    label: 'Conversion rate',
    data: campSourceDataCr.slice(0, displayCount)
  }]
}
var chartOptions = { ... }

var ctx = document.getElementById('chart2').getContext('2d');
window.chart2 = new Chart(ctx, {
  type: 'horizontalBar',
  data: chartData,
  options: chartOptions
});

Leave a comment