JS XHR loaded content - chart not displaying
makrmark opened this issue · comments
My Chartkick chart is not rendering when opening in a dynamically loaded (from XHR request) Bootstrap Modal.
This is the partial for the chart
<div class="card bg-light">
<div class="card-body border m-2">
<%= line_chart @measure.get_chart_data, height: "100px", legend: "right" %>
</div>
</div>
The Modal is displayed as such:
<%= link_to measure.name, measure_path(measure),
remote: true, 'data-toggle': "modal", 'data-target': "#my_modal" %>
And the JS partial is simply:
container = document.getElementById("my_modal_content")
container.innerHTML = "<%= j render 'measure_modal' %>"
After displaying the Modal the chart body appears but only shows Loading.
<div id="chart-1" style="height: 100px; width: 100%; text-align: center; color: #999; line-height: 100px; font-size: 14px; font-family: 'Lucida Grande', 'Lucida Sans Unicode', Verdana, Arial, Helvetica, sans-serif;">Loading...</div>
<script>
(function() {
if (document.documentElement.hasAttribute("data-turbolinks-preview")) return;
if (document.documentElement.hasAttribute("data-turbo-preview")) return;
var createChart = function() { new Chartkick["LineChart"]("chart-1", [{"name":"Actual","data":[["2022-02-28",1000.0]]},{"name":"Target","data":[["2023-02-28",100.0]]},{"name":"Forecast","data":[["2023-02-28",100.0],["2022-06-30",700.0],["2022-11-30",325.0],["2023-01-31",175.0],["2022-08-31",550.0],["2022-12-31",250.0],["2022-07-31",625.0],["2022-09-30",475.0],["2022-10-31",400.0],["2022-04-30",850.0],["2022-03-31",925.0],["2022-05-31",775.0]]}], {"legend":"right"}); };
if ("Chartkick" in window) {
createChart();
} else {
window.addEventListener("chartkick:load", createChart, true);
}
})();
</script>
When displaying this same partial from an HTML request a canvas element is created with the actual chart rendered.
<canvas width="1728" height="200" style="display: block; box-sizing: border-box; height: 100px; width: 864px;"></canvas>
So I presume the issue is that the JS is not being called after loading the modal dialog contents via XHR - but I don't know why, or how to trigger it manually.
Any assistance would be appreciated.
Thanks.
I've switched to using this and all is well:
https://www.stimulus-components.com/docs/stimulus-chartjs/
Hey @makrmark, glad you found a solution. fwiw, setting innerHTML
won't execute <script>
tags.