Corona chart
by seankoole
HTML
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/Chart.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/Colors.js/1.2.4/colors.min.js"></script>
<div id="countries">
<div class="controls">
<select name="" id="countrySelect"></select>
<input type="number" id="five-based" value="0"> (minimum infections)
<input type="checkbox" id="zero-based"> (override minimum)
<input type="checkbox" id="deaths"> (deaths)
<button id="update">Update</button>
</div>
<div id="chart">
<canvas id="myChart"></canvas>
</div>
</div>
SCSS
#countries {
min-height: 100%;
.controls {
background-color: #f1f1f1;
padding: 20px;
margin-bottom: 10px;
}
#chart {
width: 100%;
height: 80%;
}
}
JavaScript
/* Get the data from the API and init the system */
$.getJSON('https://pomber.github.io/covid19/timeseries.json', (data) => init(data));
/* Set up some dom selectors with jQuery for ease of use */
var $countrySelect = $('#countrySelect').on('change', (e) => {
var country = getCountryByName(e.target.value);
addCountryToChart(country);
configureDaysInChart(global.countries);
});
var $zeroBased = $('#zero-based').on('click', (e) => {
configureDaysInChart(global.countries);
});
var $fiveBased = $('#five-based').on('change', (e) => {
var number = parseInt(e.target.value, 12);
global.offset = number <= 0 ? 0 : number;
configureDaysInChart(global.countries);
});
var $deaths = $('#deaths').on('click', (e) => {
global.datapoint = $deaths.is(':checked') ? 'deaths' : 'confirmed';
configureDaysInChart(global.countries);
});
var $update = $('#update').on('click', (e) => {
e.preventDefault();
updateChart();
});
/* Utilities */
var getCountryByName = (name) => {
return global.countries.find(country => {
return country.name == name;
});
}
var updateChart = () => {
global.chart.update();
}
var setupChart = () => {
var ctx = document.getElementById('myChart').getContext('2d');
return new Chart(ctx, {
type: 'line',
responsive: true,
maintainAspectRatio: true,
data: {
labels: [],
datasets: [],
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
var init = (data) => {
/**
* Set up the correct countries
*/
$.each(data, (key, value) => {
global.countries.push({
name: key,
data: value,
});
});
global.countries.sort((a, b) => (a.name > b.name) ? 1 : -1)
configureDaysInChart(global.countries);
configureCountrySelect(global.countries);
}
var configureDaysInChart = (countries) => {
/* Generate the days within all */
if ($zeroBased.is(':checked')) {
...