Skip to content Skip to sidebar Skip to footer

Chart.js Modal Window

I'm trying to display a bar graph onto a pop-up modal window. I have managed to get the modal to work with a button but the graph won't appear. Modal and button:

Solution 1:

I took your code into the editor, added the Chart.js library via it's cdn, and the error was data, (or labels if I remove data) not being defined. It seems like you are trying to define data, and labels, but doing so inside the function renderChart()

With those arguments not required or passed to the function, it looks like the chart data is being rendered fine! Check out my working example:

functionrenderChart() {     
        var ctx = document.getElementById("myChart").getContext('2d');
        var myChart = newChart(ctx, {
            type: 'bar',
            data: {
                labels: [
                "GFA","GBA","NSA","FSR","Open Space Ratio","Sunlight Ratio","Ventilation Ratio","Stories"
                ],
                datasets: [{
                    label: this.labels,
                    data: [ 2.6, 30.6, 5.6, 6.4, 8.7, 2.1, 3.5, 9],
                    borderColor: 'rgba(75, 192, 192, 0.2)',
                    backgroundColor: 'rgba(75, 192, 192, 1)',
                }]
            },
        });
    }
    var modal = document.getElementById("myModal");
    var btn = document.getElementById("btn");
    var span = document.getElementsByClassName("close")[0];

    btn.onclick = function () {
        modal.style.display = 'block'renderChart();
    }

    span.onclick = function() {
        modal.style.display = 'none';
    }

    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = 'none';
        }
    }
.modal {
  border: 1px solid black;
  display: none;
}
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script><body><buttonid = 'btn'class= 'button'> 
        Data
    </button><divid = "myModal"class="modal"><divclass="modalContent"><spanclass = "close">&times;</span><canvasid="myChart"></canvas></div></div></body><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script>

Note that I also had to change the labels property to this.labels referring to the labels on the same object which it had been defined on.

Hopefully this helps get you on track

Post a Comment for "Chart.js Modal Window"