Javascript keyboard, shift + key combo

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:

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

Upvotes: 2

Views: 1156

Answers (1)

Bic
Bic

Reputation: 3134

Your code has an error in it, that is caused by the keypress event. The event is continuously firing whenever you are holding the shift key down. However, String.fromCharCode(e.which) will always return an empty string for Shift, which is not a printable character. You need to add logic to your keypress event to handle shift:

var bokstav = function(e) {
    e = e || window.event;
    var b = String.fromCharCode(e.which).toLowerCase();

    if (b) { // make sure b has a value
        if (shift === true) {
            document.getElementById(b).className += (farge2);
        } else {
            document.getElementById(b).className += (farge1);
        }
    }
};

To prevent shift from changing on a normal keyup:

document.getElementById(b).className = ("");
if (k === 16) {
    document.getElementById('shift-left').className = ("");
    document.getElementById('shift-right').className = ("");
    shift = false;
} 

Here is a Fiddle. This will only work for the 'a' or 'shift' + 'a' presses.

Upvotes: 3

Related Questions