Resize the charts programmatically


#1

Hi community, I’m trying to readjust the size of the charts depending of some events (open or close sidebars, panels, etc) I change the the size of the div with jquery in this way:
$('#chart div').height('200px')
The div is updated with the new size but the chart do not get resized, what I have to do in this case. thanks.


#2

Hi @ryan if your chart don’t get resized automatically when do you change the parent div size you can get the chart instance and call the resize method. For example as in your previous comment if the div that contains your chart has the id “chart” you cand do:

cf.getVisualization('chart').resize();

Let me know if this anwer your question. Best regard.


#3

It works!!! One more question: is there a way to detect the change of the div size automatically and call the resize method on the visual?


#4

Hi @ryan that question Is not directly related with ChartfFactor Toolkit but I can give you and advice, you can use the emerging Resize Observer API, available since Chrome 64 or a library more supported on other browsers like css-element-queries: https://marcj.github.io/css-element-queries/ one example with that library is the following:

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>Simple Resize Demo</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/css-element-queries/1.1.1/ResizeSensor.min.js"></script>
    <script src="cftoolkit.min.js"></script>
    <script src="cft-standard-charts.min.js"></script>
    <style type="text/css">
        #resizable {
          resize: both;
          overflow: auto;
          width: 250px;
          height: 200px;
          border: 1px solid black;
        }
    </style>
</head>
<body>
     <div id="resizable"></div>
     
    <script type="text/javascript">
        var elmId = 'resizable';
        var data1 = {
        groups: ['Brand'],
        metrics: ['Speed'],
        data: [
            { group: ['Peugeot' ], current: { metrics: { Speed: 40}}},
            { group: ['Renault' ], current: { metrics: { Speed: 50}}},
            { group: ['Ferrari'], current: { metrics: { Speed: 100}}},
            { group: ['Lamborghini'], current: { metrics: { Speed: 120}}}
        ]
    };
    
    var chart1 = cf
                .create()
                .bars()
                .element(elmId)
                .data(data1);
    chart1.execute();
        
       var element = document.getElementById(elmId);
        new ResizeSensor(element, function() {
            console.log(`Width changed to: ${element.clientWidth}, and height changed to: ${element.clientHeight}.`);
            chart1.resize();
        });
    </script>
</body>
</html>

You have to copy the ChartFactor Toolkit library and the Standard Charts package into the same directory of the html file of the example and you could resize the div and see how the chart resize immediately. I hope this help. Best regards.