Back to amCharts.com

Controlling chart with JavaScript

You can use JavaScript commands to control the chart. This allows you to create a way for your viewers to manipulate the chart from the web page, as well as to retrieve some information from the chart, so you can synchronize another element of the page with the chart.

For a better understanding, open examples/javascript_control/index.html from the Stock chart package you downloaded, and try to click on some buttons below the chart.

Please Note: Javascript controls will only work once you have uploaded the files to your web server - they will not work if you are viewing the chart on your hard drive.

JS functions are cued. You may call several JS functions at a time, without waiting for the previous one to finish. All called functions will be executed in turn.

Finding when the chart is initialized

Before you can start controlling the chart with JavaScript, the SWF, settings and data files must be fully loaded. When the chart is loaded, it calls a JavaScript function:

amChartInited(chart_id)

The chart_id is useful only if you have more than one chart on a page and need to know which chart is initialized. This chart_id variable must be set in the HTML, by adding the following line to the source (somewhere above the so.write(flashcontent) line):

so.addVariable("chart_id", "chart1");

The "chart1" is an ID, which can be any number/letter combination, and must be unique for every chart on the page. When the amChartInited function is called, it receives this chart_id variable. To reduce confusion, you can use the same ID as your Flash object's. The Flash object ID is set in the following line, the second parameter:

var so = new SWFObject("../amstock/amstock.swf", "chart1", "1000", "700", "8", "#FFFFFF");

When this function is called, you should get the Flash object into a variable, so you can use it to call functions when controlling the chart. Here is the function to do it:

function amChartInited(chart_id){
  flashMovie = document.getElementById(chart_id);
}

Note that if your Flash object ID is not the same as your chart_id variable, this won't work, and you will have to use the getElementById function with the real Flash object ID.

In order to be sure that you got the Flash object, try to alert the flashMovie variable, by adding alert(flashMovie) into this function. Now, the message with the text [object] should pop up when you refresh your browser.

For advanced users: If you have more than one chart on a page, you should get every Flash object into a separate variable. You can create an object and assign instances to its properties:

var flashMovie = new Object();
 
function amChartInited(chart_id){
   flashMovie[chart_id] = document.getElementById(chart_id);
}
Back to top