I'm creating a on-screen-keyboard in vanilla Javascript and I'm trying to change the color of the on-screen-keyboard-keys when the same keys are pressed on the physical keyboard. So far so good. The problem is, I am using keyup and keydown, but I can't seem to get the shift-combos right.
This is whats going to happen:
- When a normal key is pressed it changes color to blue.
- When the shift-key is pressed it changes color to red.
- When the shift-key + a key is pressed, both of them is going to be red, and when the key is released it is going back to normal, but if the shift-key is still being held down it will have the color red.
Problem: When the shift-key is pressed + a normal key, the color on both buttons will dissapear if I release the normal key, even if the shift-key is still pressed.
This is my code so far:
farge1 = ' key-pressed';
farge2 = ' shift-pressed';
shift = false;
var klikk = function(e) {
e = e || window.event;
var k = e.keyCode || e.which;
if (k === 13) {
document.getElementById('enter').className += (farge1);
} else if (k === 8) {
document.getElementById('backspace').className += (farge1);
} else if (k === 16) {
document.getElementById('shift-right').className += (farge2);
document.getElementById('shift-left').className += (farge2);
shift = true;
}
};
var bokstav = function(e) {
e = e || window.event;
var b = String.fromCharCode(e.which).toLowerCase();
if (shift === true) {
document.getElementById(b).className += (farge2);
} else {
document.getElementById(b).className += (farge1);
}
};
var slipp = function(e) {
e = e || window.event;
var k = e.keyCode || e.which;
var b = String.fromCharCode(e.which).toLowerCase();
document.getElementById('enter').className = ("");
document.getElementById('backspace').className = ("");
document.getElementById(b).className = ("");
if (k !== 16) {
document.getElementById('shift-left').className = ("");
document.getElementById('shift-right').className = ("");
}
shift = false;
};
document.onkeypress = bokstav;
document.onkeydown = klikk;
document.onkeyup = slipp;
I'm totally new at this.. No jQuery pls