0

i'm trying to make buttons in GoogleCharts that can modify the "view" property of a chart.

Here's my head :

<script type="text/javascript">
    google.charts.load('current', {'packages':['corechart', 'table', 'gauge', 'controls']});
    google.charts.setOnLoadCallback(drawChart);

    function drawChart() {

        //New chart, with a specific 'view'
        var chart = new google.visualization.ChartWrapper({
            'chartType': 'ColumnChart',
            'containerId': 'chart_div',
            'options': {
                'width': 640,
                'height': 480
            },
            'view': {'columns': [0, 1]} 
        });

        //Data used to fill the chart, i don't think there's an issue here
        ...
        //There's 3 columns of data

        //Assign data to the chart and draw it
        chart.setDataTable(data);
        chart.draw();
    }
</script>

In the body i use the following function linked to a button :

<script type="text/javascript">
    function changeVisualisation() {
        chart.setView({'columns': [0, 2]});
        chart.draw();
    }
</script>       

However i get the following error :

"categoryfilter.html:54 Uncaught ReferenceError: chart is not defined"

What am i forgeting ?

1 Answers1

0

Your problem is about scope.

In Javascript, when you declare a variable inside a function you cannot use it outside this function, outside the scope.

check this :

<script>
var a = "foo";

function newScope() {
    // can access 'a'
    console.log(a) // "foo"

    var b = "bar";
} // outside this function, no one knows 'b'
</script>

little schema (not by me !)

That is the reason why your error message is chart is not defined, because you are trying to use it outside the scope.

EDIT : don't have so much time, sorry. You can read this : http://www.sitepoint.com/demystifying-javascript-variable-scope-hoisting/

Clément Flodrops
  • 1,114
  • 1
  • 13
  • 29
  • I see. I removed the 'var' in front of the declaration of 'chart', and it worked. I have no idea why thought. –  Mar 16 '16 at 11:43
  • By removing the "var" keyword, you have created a global variable, which is available everywhere. That's not a ground practice. You can use this answer to understand more deeply how it worls : http://stackoverflow.com/questions/4862193/javascript-global-variables – Clément Flodrops Mar 16 '16 at 11:45
  • I understand. Thanks. –  Mar 16 '16 at 12:13