Here is an example that sets the color first in CSS and uses javascript addEventListener to listen for a click event and changes the color of the button when clicked, it also removes the attached event listener.
CSS
#a {
background-color: yellow;
}
HTML
<button id="a">My Button</div>
Javascript
document.getElementById("a").addEventListener("click", function onClick() {
this.removeEventListener("click", onClick);
this.style.backgroundColor = "#004f40";
}, false);
On jsfiddle
This example uses the mouse click event, but you will need to look at key events instead of a mouse one, it could be one of many; e.g. keydown, keypress, or keyup.
Update: Here is one possible solution using key events.
CSS
button {
background-color: yellow;
}
Javascript
var start = 97,
end = 122,
button;
while (start <= end) {
button = document.createElement("button");
button.id = button.textContent = String.fromCharCode(start);
document.body.appendChild(button);
start += 1;
}
document.addEventListener("keypress", function onKeypress(evt) {
var element = document.getElementById(String.fromCharCode(evt.charCode || evt.char));
if (element) {
document.addEventListener("keyup", function onKeyup() {
document.removeEventListener("keyup", onKeyup);
element.style.backgroundColor = "yellow";
}, false);
element.style.backgroundColor = "#004f40";
}
}, false);
On jsfiddle
Note: this example is by no means perfect, it it just an example of how to use events.
Update: here is another example that uses all 3 events to de-bounce the keyboard when multiple keys are pressed and released. (Compare it in use with above.)
CSS
button {
background-color: yellow;
}
button:active {
background-color: #004f40;
}
Javascript
var start = 97,
end = 122,
button;
while (start <= end) {
button = document.createElement("button");
button.id = button.textContent = String.fromCharCode(start);
document.body.appendChild(button);
start += 1;
}
var keydown,
keypress = [];
document.addEventListener("keydown", function onKeydown(e1) {
keydown = e1;
}, false);
document.addEventListener("keypress", function onKeypress(e2) {
var record = {
"char": e2.char || e2.charCode,
"key": keydown.key || keydown.keyCode || keyDown.which,
"shiftKey": keydown.shiftKey,
"metaKey": keydown.metaKey,
"altKey": keydown.altKey,
"ctrlKey": keydown.ctrlKey
},
element = document.getElementById(String.fromCharCode(e2.charCode || e2.char));
if (element) {
element.style.backgroundColor = "#004f40";
keypress.push(record);
}
}, false);
document.addEventListener("keyup", function onKeyup(e3) {
var key = e3.key || e3.keyCode || e3.which;
keypress.forEach(function (record) {
if (record.key === key && record.shiftKey === e3.shiftKey && record.metaKey === e3.metaKey && record.altKey === e3.altKey && record.ctrlKey === e3.ctrlKey) {
document.getElementById(String.fromCharCode(record.char)).style.backgroundColor = "yellow";
}
});
}, false);
On jsfiddle
Note: even this is not perfect as it depends on millisecond timing to match keydown and keypress events.