In this blog, we will develop a dynamic bar chart with dynamic bar colors for SharePoint online list using ChartJS.
Introduction
Chart.js is a free open-source JavaScript library for data visualization, which supports 8 chart types: bar, line, area, pie, bubble, radar, polar, and scatter.
Try samples here.
Screenshot
Lets' get started,
By following the 3 simple steps we can create the bar chart.
Step 1
Refer to the CDN files and build the UI.
<!DOCTYPE html>
<html>
</head>
<link href="../SiteAssets/style.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.3.1.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js" type="text/javascript"></script>
</head>
<body>
<div id="main">
<h2><b>Chart JS Demo</b></h2>
<canvas id="barChart"></canvas>
</div>
<script src="../SiteAssets/ChartJS.js" onload="fnGetData()"></script>
</body>
</html>
Step 2
On load get the SharePoint List items, using the fetch() method.
We need X and Y values to plot, so creating xValues & yValues array to store the list items.
barColors array to store the dynamic color for the bars, based on the data injection.
const randomColor = '#' + Math.floor(Math.random() * 16777215).toString(16);
The code to load the dataset,
var barColors = [];
var xValues = [];
var yValues = [];
function fnGetData() {
let queryURL = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('EmployeesList')/items?$select=*,Employee/Title&$expand=Employee/Title";
let payload = {
method: 'GET',
headers: {
"Accept": "application/json; odata=verbose"
},
credentials: 'same-origin'
}
fetch(queryURL, payload)
.then(response => response.json())
.then((data) => {
let items = data.d.results;
for (var i = 0; i < items.length; i++) {
xValues.push(items[i].Employee.Title);
yValues.push(items[i].ExpInYears);
const randomColor = '#' + Math.floor(Math.random() * 16777215).toString(16);
barColors.push(randomColor);
}
fnGenerateChart(xValues, yValues);
})
}
Step 3
Generate the bar chart, using the config function,
function fnGenerateChart(xValues, yValues) {
let barChart = new Chart("barChart", {
type: "bar",
data: {
labels: xValues,
datasets: [{
data: yValues,
label: 'Employee Experience in Years',
backgroundColor: barColors
}]
}
});
}
To add more functionality refer to official docs Bar Chart - ChartJS.
Check out the full code in my GitHub repo here.
Happy learning!