Chartjs custom dynamic legend - Javascript Chart.js

Javascript examples for Chart.js:Legend

Description

Chartjs custom dynamic legend

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <title>Chart.js Legend Customization - JSFiddle - JSFiddle</title> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.js"></script> 
      <script type="text/javascript" src="https://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.min.js"></script> 
      <link rel="stylesheet" type="text/css" href="https://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.min.css"> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.js"></script> 
      <style id="compiled-css" type="text/css">

.root {/*from  www  .  ja  v  a 2  s.com*/
   height: 500px;
}
.chart-container {
   display: flex;
   flex-direction: column;
   border: solid 2px red;
   height: auto;
   min-height: 100%;
   position: relative;
   width: 500px;
}
.chart {
   flex: 1;
}


      </style> 
   </head> 
   <body> 
      <div class="root"> 
         <div class="chart-container"> 
            <div class="chart"> 
               <canvas id="myChart" style="width: 100%; height: auto;"></canvas> 
            </div> 
            <div>
               This line of text should be within chart-container and it is correct
            </div> 
            <div id="js-legend"></div> 
         </div> 
      </div> 
      <script type="text/javascript">
var data = {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [
        {
            backgroundColor: "rgba(255,99,132,0.2)",
            borderColor: "rgba(255,99,132,1)",
            borderWidth: 2,
            hoverBackgroundColor: "rgba(255,99,132,0.4)",
            hoverBorderColor: "rgba(255,99,132,1)",
            data: [65, 59, 20, 81, 56, 55, 40],
        }
    ]
};
var options = {
  legend: {
    display: false,
  },
  maintainAspectRatio: false,
   scales: {
     yAxes:[{
          stacked:true,
        gridLines: {
           display:true,
          color:"rgba(255,99,132,0.2)"
        }
    }],
    xAxes:[{
          gridLines: {
           display:false
        }
    }]
  }
}
var canvas = document.getElementById("myChart");
var myChart = Chart.Bar(canvas, {
  data: data,
  options: options,
});
document.getElementById('js-legend').innerHTML = "this is a test"

      </script>  
   </body>
</html>

Related Tutorials