Skip to content

Instantly share code, notes, and snippets.

@VijayKrishna
Created March 18, 2013 03:26
Show Gist options
  • Save VijayKrishna/5184828 to your computer and use it in GitHub Desktop.
Save VijayKrishna/5184828 to your computer and use it in GitHub Desktop.
Keys n Bars
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.chart rect {
stroke: white;
fill: steelblue;
}
</style>
<title>type</title>
<div>
<h3>Type a to z in the text box</h3>
<button type="button" onclick="blink()" >Everyone!</button>
<input type="text" onkeydown="react()" />
</div>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var react = function ()
{
var x;
if(window.event) // IE8 and earlier
{
x=event.keyCode;
}
else if(event.which) // IE9/Firefox/Chrome/Opera/Safari
{
x=event.which;
}
var keychar=String.fromCharCode(x);
hitKey(keychar);
}
var width = 550,
height = 520;
var data = [];
for ( var i = 0; i <= 25; i += 1) {
data[i] = 5;
}
var color = d3.scale.category20();
var chart = d3.select("body").append("svg")
.attr("class", "chart")
.attr("width", 420)
.attr("height", height);
chart.selectAll("text")
.data(data)
.enter()
.append("text")
.attr("x", 5)
.attr("y", function(d, i) { return (i * 20) + 15; })
.text(function(d, i) { "use strict"; return String.fromCharCode(65 + i); });
chart.selectAll("rect")
.data(data)
.enter().append("rect")
.attr("x", 20)
.attr("y", function(d, i) { return i * 20; })
.attr("width", function(d, i) { "use strict"; return data[i]; })
.attr("height", 20);
var hitKey = function (char) {
"use strict";
// alert(char);
d3.selectAll("rect")
.transition()
.duration(1500)
.attr("width", function (d, i) {
if ( alpha2num(char) === i ) { data[i] = 400; }
else { data[i] = 5; }
return data[i];
})
.transition()
.delay(1000)
.attr("width", 5)
;
};
var alpha2num = function (char) {
return char.toUpperCase().charCodeAt(0) - 65;
}
var blink = function () {
"use strict";
d3.selectAll("rect")
.transition()
.duration(1500)
.attr("width", 400)
.transition()
.delay(1000)
.attr("width", 5)
;
};
var blink2 = function () {
"use strict";
d3.selectAll("rect")
.transition()
.duration(1500)
.attr("width", function (d, i) { "use strict"; data[i] += 6; data[i] = clamp(data[i]); return data[i]; });
setInterval(function () {
"use strict";
d3.selectAll("rect")
.transition()
.delay(10)
.attr("width", function (d, i) { "use strict"; data[i] -= 2; data[i] = clamp(data[i]); return data[i]; });
}, 1500);
};
var clamp = function(num) {
"use strict";
if(num <= 2) return 2;
if(num >= width) return width;
return num;
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment