1

I've been working on JavaScript on-screen keyboard kind of thing, just for experimentation. I wanted to see if I could detect which key had been pressed, and make the corresponding on-screen keyboard button change colour, similar to many online touch typing courses have. I have tried many variations of the onkeydown command, but no luck.

//doesn't seem to do anything.
document.getElementById("a").style.backgroundColor="#004f40";  

Button's id is simply it's value eg/ the A key is id="a".

Could anyone give me any ideas on how to do this?

Suh Fangmbeng
  • 573
  • 4
  • 16
  • 4
    take a look at: http://stackoverflow.com/questions/13630229/onclick-in-css – İsmet Alkan May 12 '13 at 14:30
  • put your code here or use http://jsfiddle.net – mehdi May 12 '13 at 14:31
  • Maybe I went a bit too far, but I like onscreen keyboards so made a little demo: http://jsfiddle.net/3aQZG/. I strongly suggest using jQuery in your case (can articulate if the demo fulfills your needs). The keyboard is a bit long, but at the end of it you have the input to catch keydon / up events (fiddle catches those events on body so had to use a target input field). – sixFingers May 12 '13 at 14:47
  • Did you ever get an answer to your problem? If you did, consider sharing it with us. – Xotic750 Jun 12 '13 at 10:45

2 Answers2

1

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.

Xotic750
  • 22,914
  • 8
  • 57
  • 79
-1

Or alternatively, you could use jQuery:

    $(".keyboardButton").mousedown(function(){
      $(this).css("background":"#Color-when-pressed");
    }

    $(".keyboardButton").mouseup(function(){
      $(this).css("background":"#Color-when-released");
    }

Of course, replace the colors respectively.
Get jQuery

Or pure CSS:

   .keyboardButton:active {
     background:#Color-when-pressed;
   }
   .keyboardButton {
     background:#Color-when-released;
   }

It might be the best, since you won't have to write code for every single button you have, and you probably already have CSS classes for them.

Kkarsko
  • 103
  • 1
  • 7
  • I forked sixFingers' fiddle to use the pure CSS method above: http://jsfiddle.net/JFnKp/ – Kkarsko May 12 '13 at 14:59
  • Your jquery example should be using ´keydown´ and ´keyup´: http://api.jquery.com/category/events/keyboard-events/ It also has a syntax error as the ":" after "background" should be a ",". Finally with this fixed, your example has the same key bounce issue as my second example. Also, your CSS example only works on mouse clicks and not key presses. – Xotic750 May 12 '13 at 19:49