Skip to content

Instantly share code, notes, and snippets.

@ajfarkas
Last active October 23, 2019 22:19
Show Gist options
  • Select an option

  • Save ajfarkas/0767aad90dd57ee7490e9f6256b5b683 to your computer and use it in GitHub Desktop.

Select an option

Save ajfarkas/0767aad90dd57ee7490e9f6256b5b683 to your computer and use it in GitHub Desktop.
Bar Chart Clock

#Bar Chart Clock

Sometimes D3 is overkill. For a simple bar chart that changes value (this example uses time), defining the width of the bar as a percentage of its container will suffice. 14 lines gets the job done.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<style>
* {
margin: 0;
padding: 0;
border: none;
}
#graph {
width: 960px;
height: 480px;
}
.bar {
width: 0;
height: 150px;
margin: 5px 0;
overflow-y: visible;
font-size: 48px;
color: #9c3c3c;
text-transform: uppercase;
transition: width 0.8s linear;
}
.hour { background-color: #342474; }
.minute { background-color: #426cc9; }
.second { background-color: #52dadb; }
</style>
</head>
<body>
<div id="graph">
<p class="hour bar"></p>
<p class="minute bar"></p>
<p class="second bar"></p>
</div>
</body>
<script>
function getTime() {
var now = new Date()
var time = {
hour: now.getHours() % 12,
minute: now.getMinutes(),
second: now.getSeconds()
}
Object.keys(time).forEach(function(hand) {
var max = hand === 'hours' ? 12 : 60
document.querySelector('.'+hand).style.width = 100*time[hand]/max + '%'
document.querySelector('.'+hand).innerHTML = time[hand]+'&nbsp;'+hand+'s'
})
}
var timer = window.setInterval(getTime, 1000)
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment