[Chartjs]-Chart.js change height on window resize while maintaining aspect ratio

0๐Ÿ‘

โœ…

I found a way here to resize the chart by loading it again to refresh the new height, tho it may not be the best practice. Also found a way to link each bar and send a parameter to another page. see the codes bellow.

in my dashboard.php:

<script>
window.onresize=function(){
    $("#container").load("chart1.php");
}

$("#container").load("chart1.php");
</script>

in chart1.php:

<?php
//myqueries here for $ch1_arrDate,$ch1_arrRevenue_conf, and $ch1_arrDate2
?>
<div>
    <canvas id="chart1" width="500" height="300"></canvas>
</div>


<script>
$(document).ready(function(){
var barLabel = <?php echo json_encode(array_reverse( $ch1_arrDate)); ?>;
var dataVal1 = <?php echo json_encode(array_reverse( $ch1_arrRevenue_conf)); ?>;
var dateFilter = <?php echo json_encode(array_reverse($ch1_arrDate2)); ?>;

var barData = {
    labels: barLabel,
    datasets: [
        {
            label: 'Confirmed Revenue',
            backgroundColor: 'yellowgreen',
            data: dataVal1,
        },
    ]
};

var barOptions = { 
    responsive: true,
    maintainAspectRatio: true
}


var ctx = document.getElementById("chart1").getContext("2d");

if($(window).width()>748)
    ctx.canvas.height = 160;
else
    ctx.canvas.height = 300;

var chartDisplay = new Chart(ctx, {
    type: 'bar',
    data: barData,
    options: barOptions
});

$("#chart1").click( 
   function(e){
        var activeBars = chartDisplay.getElementsAtEvent(e);
        var index = activeBars[0]["_index"];
        location.href="dash_chartdeals.php?filter_date="+fixedEncodeURIComponent(dateFilter[index]);
});
});
</script>

Leave a comment