Chart.js Charts from HTML Data Attributes

Example HTML

<canvas 
    class="chart" 
    data-type="horizontalBar" 
    data-labels="[&quot;White&quot;, &quot;Blue&quot;, &quot;Black&quot;, &quot;Red&quot;, &quot;Green&quot;, &quot;Colorless&quot;]" 
    data-series="[13, 11, 5, 2, 2, null]"></canvas>

JavaScript

$('.chart').each(function () {
    var id = $(this).attr("id"),
        type = $(this).data("type"),
        labels = $(this).data("labels"),
        series = $(this).data("series"),
        options = $(this).data("options"),
        ctx = this.getContext("2d");
    new Chart(ctx, {
        'type': type,
        'data': {
            labels: labels,
            datasets: [{
                data: series
            }]
        },
        options: options
    });
});

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.