Because why not?
Last active
April 14, 2017 19:53
-
-
Save HarryStevens/6c4b74a88b984d9d9a4f54d1442c13a9 to your computer and use it in GitHub Desktop.
jQuery Bar Chart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
license: gpl-3.0 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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