Skip to content

Instantly share code, notes, and snippets.

@HarryStevens
Last active Apr 14, 2017
Embed
What would you like to do?
jQuery Bar Chart
license: gpl-3.0

Because why not?

<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: "Helvetica Neue", sans-serif;
}
.axis-label {
position: absolute;
}
.rect {
left: 0;
position: absolute;
background: steelblue;
text-align: right;
color: #fff;
}
.rect:hover {
background: red;
}
.label {
margin-right: 10px;
margin-top: 10px;
}
</style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var width = 400,
barHeight = 40,
barPadding = 2,
margin = {top: 10, bottom: 0, left: 50, right: 0}
$("body")
.append("<div class='chart'></div>");
var data = [{
name: "Bob",
value: 3
},{
name: "Sally",
value: 5
},{
name: "Jim",
value: 2
}];
// calculate max value
var max = data
.map(function(d){ return d.value; })
.sort()
.reverse()[0];
// x scale
function x(val){
return (val / max) * width;
}
// loop through the data and describe the encodings of the data attributes
data.forEach(function(d,i){
$(".chart")
.append("<div class='rect rect-" + i + "' />");
$(".rect-" + i)
.css({
"width": x(d.value),
"height": barHeight,
"top": (barHeight + barPadding ) * i + margin.top,
"left": margin.left
});
$(".rect-" + i)
.append("<div class='label'>" + d.value + "</div>");
$(".chart")
.append("<div class='axis-label axis-label-" + i + "'>" + d.name + "</div>");
$(".axis-label-" + i)
.css({
"top": (barHeight + barPadding ) * i + margin.top + 10,
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment