Very Simple Responsive Bar Chart – Free Code Download

Welcome to a tutorial on how to create a simple responsive bar chart. So you may be looking for ways to create bar charts, but do not want to load any of those bloated complicated libraries. So here it is, a simple lightweight bar chart using only pure CSS and Javascript – Read on!

ⓘ I have included a zip file with all the example code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

TABLE OF CONTENTS

Download & Notes Horizontal Bar Chart Vertical Bar Chart
Useful Bits & Links The End

 

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

HORIZONTAL BAR CHART

All right, let us now get started with the simpler version – The horizontal bar chart.

 

HORIZONTAL BAR CHART DEMO

 

 

STEP 1) QUICKSTART – THE HTML

1-horizontal.html
<!-- (A) LOAD HORIZONTAL BAR SCRIPTS -->
<link rel="stylesheet" href="1-horizontal.css"/>
<script src="1-horizontal.js"></script>
 
<!-- (B) DIV TO GENERATE BAR CHART -->
<div id="demoA"></div>

<!-- (C) CREATE CHART ON PAGE LOAD -->
<script>
window.addEventListener("DOMContentLoaded", function(){
  hbar("demoA", [
    ["First", 33],
    ["Second", 100],
    ["Third", 50]
  ]);
});
</script>

For you guys who just want to use this as a “plugin” without reading all the rest of the tutorial:

  • A – Captain Obvious, load the CSS and Javascript files.
  • B – Create a <div> container to hold the bar chart.
  • C – Use hbar(TARGET, DATA) on window load to generate the bar chart.
    • TARGET Where to generate the bar chart, the ID of the HTML element.
    • DATA Multi-dimensional array in the format of [[LABEL, AMOUNT], [LABEL, AMOUNT], ...].

That’s all – The GZIPPED and minified Javascript and CSS should fall under 1KB.

 

 

STEP 2) THE CSS

Before we dive into the CSS, here are 2 things that the Javascript will do to create the bar chart:

  • Add a .hbar CSS class to the container.
  • Add <div> for the individual bars, set the width and background.
<div id="demoA" class="hbar">
  <div style="width: 33%; background:COLOR">First: 33</div>
  <div style="width: 100%; background:COLOR">Second: 100</div>
  <div style="width: 50%; background:COLOR">Third: 50</div>
</div>

So for the very simple CSS:

1-horizontal.css
/* (A) BAR CHART CONTAINER */
.hbar {
  width: 100%;
  border: 1px solid #333;
  background: repeating-linear-gradient(
    to right, #f2f2f2, #ddd 2px, #fff 2px, #fff 5%
  );
}
 
/* (B) EACH INDIVIDUAL BAR */
.hbar div {
  box-sizing: border-box;
  padding: 10px;
  margin: 5px 0;
  color: #fff;
}

Feel free to modify to your own needs.

 

 

STEP 3) THE JAVASCRIPT

1-horizontal.js
function hbar (target, data) {
  // (A) INIT HTML CONTAINER
  target = document.getElementById(target);
  target.classList.add("hbar");
  target.innerHTML = "";
 
  // (B) GET LARGEST VALUE FROM DATA
  var largest = 0;
  data.forEach(el => {
    if (el[1] > largest) { largest = el[1]; }
  });
 
  // (C) DRAW THE BARS
  var bars = new DocumentFragment(), bar = null;
  data.forEach(el => {
    // (C1) CREATE NEW BAR
    bar = document.createElement("div");
    // (C2) CALCULATE WIDTH OF BAR
    bar.style.width = Math.ceil((el[1] / largest) * 100) + "%";
    // (C3) RANDOM BACKGROUND COLOR
    bar.style.background = randcol();
    // (C4) TEXT
    bar.innerHTML = el[0] + ": " + el[1];
    // (C5) ADD BAR TO CONTAINER
    bars.appendChild(bar);
  });
  container.appendChild(bars);
} 
 
// (D) HELPER FUNCTION - GENERATE RANDOM DARK COLOR
// SOURCE: https://gist.github.com/Chak10/dc24c61c9bf2f651cb6d290eeef864c1
function randcol () {
  var lum = -0.25;
  var hex = String('#' + Math.random().toString(16).slice(2, 8).toUpperCase()).replace(/[^0-9a-f]/gi, '');
  if (hex.length < 6) {
    hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
  }
  var rgb = "#", c, i;
  for (i = 0; i < 3; i++) {
    c = parseInt(hex.substr(i * 2, 2), 16);
    c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
    rgb += ("00" + c).substr(c.length);
  }
  return rgb;
}

Not going to walk through the Javascript line-by-line, but essentially:

  • A – Get the specified target container, attach the .hbar CSS class.
  • B – Get the largest value from the data set.
  • C – Loop through the data, generate the individual bars.

 

VERTICAL BAR CHART

Next, let us move on with creating a vertical bar chart – This one is actually a tad bit different and challenging than the horizontal one.

 

VERTICAL BAR CHART DEMO

 

 

STEP 1) QUICKSTART – THE HTML

2-vertical.html
 <!-- (A) LOAD VERTICAL BAR SCRIPTS -->
<link rel="stylesheet" href="2-vertical.css"/>
<script src="2-vertical.js"></script>
 
<!-- (B) CREATE DIV -->
<div id="demoB"></div>
 
 <!-- (C) ATTACH ON PAGE LOAD -->
<script>
window.addEventListener("DOMContentLoaded", function(){
  vbar("demoB", [
    ["First", 33],
    ["Second", 100],
    ["Third", 50]
  ]);
});
</script>

For you guys who just want to use this as a “plugin”, it’s the same story again:

  • A – Load the CSS and Javascript.
  • B – Create a <div> container to hold the bar chart.
  • C – Use vbar(TARGET, DATA) on window load to generate the bar chart.

 

STEP 2) THE CSS

The generated HTML for the vertical bar chart is slightly different:

  • A .vbar CSS class will be added to the container.
  • Each individual bar will be a <div class="vcell"><div></div></div>. Yes, that is 2 <div> per bar.
<div id="demoB" class="vbar">
  <div class="vcell" style="width: 33.33%;">
    <div style="background:COLOR; height:HEIGHT">First: 33</div>
  </div>
  <div class="vcell" style="width: 33.33%;">
    <div style="background:COLOR; height:HEIGHT">Second: 100</div>
  </div>
  <div class="vcell" style="width: 33.33%;">
    <div style="background:COLOR; height:HEIGHT">Third: 50</div>
  </div>
</div> 

For the CSS:

2-vertical.css
/* (A) BAR CHART CONTAINER */
.vbar {
  display: table;
  width: 100%;
  height: 400px;
  border: 1px solid #333;
  background: repeating-linear-gradient(
    to bottom, #f2f2f2, #ddd 2px, #fff 2px, #fff 10%
  );
}
 
/* (B) EACH INDIVIDUAL BAR */
.vcell {
  display: table-cell;
  vertical-align: bottom;
  text-align: center;
  color: #fff;
}
  • A – Basically, we need to set the .vbar container to display: table and give it a fixed height. The rest is just cosmetics.
  • B – The height of the individual bars will be automatically calculated by Javascript. The important part here is to set .vcell { display: table-cell; vertical-align: bottom }.

 

 

STEP 3) THE JAVASCRIPT

2-vertical.js
function vbar (target, data) {
  // (A) INIT HTML CONTAINER 
  target = document.getElementById(target);
  target.classList.add("vbar");
  target.innerHTML = "";
 
  // (B) GET LARGEST VALUE
  var largest = 0;
  data.forEach(el => {
    if (el[1] > largest) { largest = el[1]; }
  });
 
  // (C) CALCULATE HEIGHT RATIO + WIDTH
  var ratio = container.clientHeight / largest,
  width = (100 / data.length).toFixed(2) + "%";

  // (D) DRAW THE BARS
  var bars = new DocumentFragment(), vcell = null, bar = null;
  data.forEach(el => {
    // (D1) OUTER CELL - <DIV CLASS="VCELL" STYLE="WIDTH:X">
    vcell = document.createElement("div"),
    vcell.classList.add("vcell");
    vcell.style.width = width;
    // (D2) INNER BAR - <DIV STYLE="BACKGROUND:COLOR; HEIGHT:X">
    bar = document.createElement("div");
    bar.innerHTML = el[0] + ": " + el[1];
    bar.style.background = randcol();
    bar.style.height = Math.floor(ratio * el[1]) + "px";
    // (D3) ATTACH BAR TO CONTAINER
    vcell.appendChild(bar);
    bars.appendChild(vcell);
  });
  container.appendChild(bars);
}

Yep, this looks intimidating, but it is essentially just some calculations and creating the bars again:

  • A – Get the target container, attach .vbar CSS class.
  • B – Get the largest value from the data set.
  • C – Calculate the width and height ratio of the individual bars.
  • D – Loop through the data, create the individual bars.

 

USEFUL BITS & LINKS

That’s all for this guide, and here is a small section on some extras and links that may be useful to you.

 

INFOGRAPHIC CHEAT SHEET

Horizontal Bar Chart CSS JS (Click to Enlarge)

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has given you some good ideas on how to create your bar charts, and if you have anything to add to this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *