Getting Javascript charts working in Squarespace

This is an example of a realtime chart created using canvasjs in javascript. 

The following notes show how to adapt the code example to work inside Squarespace.

Firstly, you'd need to upload the canvasjs.min.js script to your site.  See http://help.squarespace.com/guides/uploading-and-managing-files for instructions. 

When you upload the files they go to a /s/ folder and also, all but the last dot will be stripped from the filename. 

This means canvasjs.min.js will be uploaded to /s/canvasjsmin.js

Now insert the following code into the header injection point of the page you want the chart to appear

<script type="text/javascript">
window.onload = function () {

var dps = []; // dataPoints

var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Live Random Data"
},
data: [{
type: "line",
dataPoints: dps 
}]
});

var xVal = 0;
var yVal = 100;
var updateInterval = 20;
var dataLength = 500; // number of dataPoints visible at any point

var updateChart = function (count) {
count = count || 1;
// count is number of times loop runs to generate random dataPoints.

for (var j = 0; j < count; j++) {
yVal = yVal +Math.round(5 + Math.random() *(-5-5));
dps.push({
x: xVal,
y: yVal
});
xVal++;
};
if (dps.length > dataLength)
{
dps.shift();
}

chart.render();

};

// generates first set of dataPoints
updateChart(dataLength); 

// update chart after specified time. 
setInterval(function(){updateChart()}, updateInterval); 

}
</script>
<script type="text/javascript" src="/s/canvasjsmin.js"></script>

Finally, in the main page body insert the following code into a code block, replacing the default content that is there. 

 <div id="chartContainer" style="height: 300px; width:100%;">
</div>

It *should* now all work. 

 

Colin Irwin

I’m Colin Irwin, a freelance Squarespace Designer & Developer based in London, UK, with clients in the USA and around the world.

I’m a recognised Squarespace expert. I design and build Squarespace sites for everyone from charities and start ups to major established brands.

https://www.silvabokis.com
Previous
Previous

Why I removed my Squarespace SEO description. And why you should too.

Next
Next

Adding autoplay video banners to a Squarespace website