I have one page HTML which part of it is:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(Social);
function Social() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('number', 'Errors');
data.addRows([
['bla', 53],
['bla', 5]
]);
var options = {title:'Social',
width:600,
height:200,
animation:{
"startup": true,
duration: 1500,
easing: 'out'}
};
var chart = new google.visualization.ColumnChart(document.getElementById('Social'));
chart.draw(data, options);}
</script>
Upon loading this page it uses google to nicely show the rows in ColumnChart.
If I would change the line starting with "var chart" to this:
var chart = new google.visualization.BarChart(document.getElementById('Social'));
The html would show barchart.
I want to create a javascript button that will replace text in the html from ColumnChart to BarChart and reload the page, something like:
function myFunction() {
document.body.innerHTML = document.body.innerHTML.replace("ColumnChart", "BarChart");
location.reload();
}
But this reload the page with the initial values. If I don't add reload I don't see any difference of course.
How can I achieve this?
It is not possible to make change and reload the page and keep the change as GET request will reload the page from the server. Instead, you want to inject a script and run it so you update the existing page, you can try to run this after the page as loaded to overwrite the ColumnChart :
function socialBarChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('number', 'Errors');
data.addRows([
['bla', 53],
['bla', 5]
]);
var options = {
title:'Social',
width: 600,
height: 200,
animation: {
"startup": true,
duration: 1500,
easing: 'out'
}
};
var chart = new google.visualization.BarChart(document.getElementById('Social'));
chart.draw(data, options);
}
// Then call this :
socialBarChart()
It is best practice to use camelCase with a lowercase first char for naming your function, otherwise, it look like a class constructor.