Chartjs-Chart.js only displays on refresh in Rails app

0👍

this is how I got working my chart.js with turbolinks

    var ready = function() {

  $.ajax({
        url: "myurl.json",
        type: "get",
        async: true,
        datatype : 'string'
        }).done (function (data) {

          var years = [];
          var obstaravania = [];
          var trzby = [];
          var zisk = [];
          var obstarcolor=[];
          var trzbycolor=[];
          var ziskcolor=[];
      for(var i in data) {
        years.push(data[i].year);
        obstaravania.push(data[i].obstaravanie);
        trzby.push(data[i].trzby);
        zisk.push(data[i].zisk);
        obstarcolor.push('#c0392b');
        trzbycolor.push('#337ab7');
        ziskcolor.push('#27ae60');
      }
      var chartdata = {
        labels: years,
        datasets : [
          {
            label: 'Obstarávania',
            backgroundColor: obstarcolor,
            labelColor: [ '#c0392b'],
            data: obstaravania
          },
          {
           label: 'Tržby',
           backgroundColor:trzbycolor,
            labelColor: [ '#337ab7'],
           data: trzby 
          },
          {
           label: 'Zisk',
            backgroundColor:ziskcolor,
          labelColor: [ '#27ae60'], 
           data: zisk 
          }
        ]
      };
    var barOptions = {
        responsive: true
    };
      var ctx2 = $("#mychart");
    var newchart = new Chart(ctx2, {type: 'bar', data: chartdata, options:barOptions});
    });

  //});

};
 $(".contractors.showcontractor").ready(ready);
  document.addEventListener('turbolinks:before-cache', function() {
    if ($('#mychart').width >1) {newchart.destroy() ;}
     });
  $(".contractors.showcontractor").on('turbolinks:ready', ready); 

Leave a comment