code everywhere

Pure CSS/HTML bar chart

posted on March 22, 2013, 4:59 pm in js

Draw a bar chart in pure CSS/HTML with this small JavaScript snippet. No external dependancies needed.

The Code

JavaScript

/* File:    CSS/HTML Bar Chart Builder
 * Date:    March 22, 2013
 * License: MIT (http://opensource.org/licenses/MIT)
 * Copyright (C) 2013 by http://codeeverywhere.ca
 */
var uiBarChart = function(settings) {
    var
        
data settings['data'] || [],
        
labels settings['labels'] || [],
        
targetID settings['targetID'] || 'ui-chart',
        
el document.getElementById(targetID),
        
width settings['width'] || el.getAttribute('width'),
        
height settings['height'] || el.getAttribute('height'),
        
buffer '',
        
label '',
        
max Math.max.apply(0data),
        
numOfBars data.length,
        
padding settings['padding'] || 2,
        
barHeight 0,
        
top 0,
        
barWidth Math.floor((width numOfBars) - (padding)),
        
reducedData = new Array(numOfBars);

    for (var 
0numOfBarsx++)
        
reducedData[x] = Math.floor(((0.95 height) * data[x]) / max);

    for (var 
0numOfBarsi++) {
        
barHeight reducedData[i];
        
top height barHeight;
        
label labels[i] || "";
        
buffer += '<a href="#" title="' label '" style="float:left;width:' +
            
barWidth 'px;margin: 0 ' padding 'px 0 ' padding +
            
'px;margin-top:' top 'px;height:' barHeight 'px;">' label '</a>';
    }
    
el.innerHTML buffer '<div style="clear:both"></div>';
};

CSS

.uiBarChart border-bottom1px solid #bcbcbc; }
.uiBarChart a:first-child background#86b671; }
.uiBarChart a:nth-last-child(2) { background#c0ffa4; }
.uiBarChart a background#ACE494; border-top: 2px solid #9ad87f; text-align: center; color: #638b52; text-decoration : none; text-transform: capitalize; }
.uiBarChart a:hover background#c0ffa6; }

Usage

Example 1)

uiBarChart({ data : [1,2,3,4,3,2,1,2,4,8,4], targetID "ui-chart" });
<div id="ui-chart" class="uiBarChart" width="610" height="150"></div>

Example 2)

uiBarChart({ data : [9,4,2,8], targetID "ui-chart2"padding 15labels : ['gold''silver''bronze''platinum'] });
<div id="ui-chart2" class="uiBarChart" width="610" height="200"></div>

Its easy to import, the code can be quickly modify and using CSS, the look can be changed to fit any theme.

recent posts

< back
find something helpful? send us some coin BTC 19u6CWTxH4cH9V2yTfAemA7gmmh7rANgiv

(ad) Need Hosting? Try Linode, VPS Starting from $5

privacy policy