[Chartjs]-Placing JavaScript content in Bootstrap Popover

6👍

You can set the popover options in JavaScript directly, and you can also listen to events.

The important option here is html: true which enables placing HTML within the popover content, otherwise shown as a string.

The content option documentation states:

Default content value if data-content attribute isn’t present.

Then, listening to the shown.bs.popover event, we get the previously placed <canvas> with jQuery and pass it as the context for a new Chart.js instance.

$('[data-toggle="popover"]').popover({
  html: true,
  content: '<canvas id="myChart" width="400" height="400"></canvas>',
}).on('shown.bs.popover', function() {

  new Chart($('#myChart'), {
    // The type of chart we want to create
    type: 'line',

    // The data for our dataset
    data: {
      labels: ["January", "February", "March", "April", "May", "June", "July"],
      datasets: [{
        label: "My First dataset",
        backgroundColor: 'rgb(255, 99, 132)',
        borderColor: 'rgb(255, 99, 132)',
        data: [0, 10, 5, 2, 20, 30, 45],
      }]
    },

    // Configuration options go here
    options: {}
  });
});
<button type="button" class="btn btn-lg btn-primary" data-toggle="popover" title="Good vs. Evil Winrate" data-placement="bottom">Who's Winning?</button>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.bundle.min.js"></script>

Leave a comment