JSFiddle - React, Tailwind, and code Playground

by jacomyal

HTML

<div id="barchart"></div>

CSS

#barchart {
    position: absolute;
    top: 30px;
    bottom: 50px;
    left: 0;
    right: 0;
}
#barchart .bar {
    position: absolute;
    bottom: 0;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
}
#barchart .bar .title {
    position: absolute;
    bottom: 100%;
    width: 100%;
    text-align: center;
    font-family: sans-serif;
    text-overflow: ellipsis;
    overflow: hidden;
    whitespace: no-wrap;
}

JavaScript

var data = [
  { id: 'chrome',
    label: 'Chrome',
    value: 11214,
    color: '#f4b400' },
  { id: 'firefox',
    label: 'Firefox',
    value: 3012,
    color: '#ff9500' },
  { id: 'safari',
    label: 'Safari',
    value: 1243,
    color: '#53d769' },
  { id: 'explorer',
    label: 'Internet Explorer',
    value: 430,
    color: '#00a1f1' },
  { id: 'opera',
    label: 'Opera',
    value: 134,
    color: '#cc0f16' },
  { id: 'others',
    label: 'Autres',
    value: 165,
    color: '#cccccc' }
];

var barchart = document.getElementById('barchart');

// Extraction de la valeur maximale de la donnée:
var max = Math.max.apply(Math, data.map(function(obj) {
  return obj.value;
}));

// Génération des barres:
data.forEach(function(obj, i) {
  var bar = document.createElement('div');

  bar.setAttribute('class', 'bar');
  bar.setAttribute('title', obj.label + ' : ' + obj.value + ' visites');
  bar.setAttribute('data-bar-id', obj.id);

  bar.style.background = obj.color;
  bar.style.top = ((max - obj.value) / max * 100) + '%';
  bar.style.left = (i / data.length * 100) + '%';
  bar.style.width = (1 / data.length * 100) + '%';

  barchart.appendChild(bar);

  var title = document.createElement('div');
  title.setAttribute('class', 'title');
  title.innerHTML = obj.label;
  bar.appendChild(title);
});