BrettJ
BrettJ

Reputation: 1226

Placing JavaScript content in Bootstrap Popover

I'm having trouble placing JavaScript inside of my Popover. I want to place a Graph, from Chart.js, inside of the Popover when clicked. For the sake of the example lets use the example graph from their documentation http://www.chartjs.org/docs/latest/

So far I have my Popover -

<button type="button" 
        class="btn btn-lg btn-primary" 
        data-toggle="popover" 
        title="Good vs. Evil Winrate" 
        data-placement="bottom" 
        data-content="Graph coming soon!">
    Who's Winning?
</button>

And the jQuery to initialize it -

$(document).ready(function(){
    $('[data-toggle="popover"]').popover();
});

I just don't understand how to place the graph inside of the Popover, everything I've tried breaks it to a point of the Popover not opening at all.

Upvotes: 6

Views: 3457

Answers (1)

Emile Bergeron
Emile Bergeron

Reputation: 17430

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>

Upvotes: 8

Related Questions