pi.314
pi.314

Reputation: 620

keyboard events: Keyup give unconsistent behaviour

I have an issue with keyboard key-up events in Javascript (checked on chrome).

Presented below 4 parts are pleaced in four different files, attach together. And it works quite fine but has one strange behaviour.

Look at the code and please focus on marked line:

MAIN.JS

document.addEventListener("DOMContentLoaded", function() {
    document.onkeyup = function(event){
        EVENT_KEYBOARD(event);
    }
}

EVENTS:

function EVENT_KEYBOARD(event) {
    LOG_DEBUG("key pressed." + event.key + " code"+event.keyCode);
    main_controller.event_keyboard_click(event);
}

CONTROLLER:

this.event_keyboard_click = function(event) {
    keyCode = event.keyCode;
    key = event.key;
    if(keyCode == 44){ myCanvas.abond_for_a_while(3000);}// PRINT SCREEN
    else if(keyCode == 27){ myConsolas.cursorEscape();} // ESCAPE
    ...
    else if(key == "Delete"){myConsolas.cursorDelete();}
    else {myConsolas.workForMe(event);}
}

CONSOLAS.JS :

this.workForMe = function(event) {
    key=event.key.toUpperCase();
// THIS LINE BELOW:
    if((key.length==1&&key>='0'&&key<='Z') || ",*-_ ;\'".includes(event.key)){
        ...
    }
}

And now lets consider four chars which are pleaced on two buttons on my (phisical) keyboard:

when i press 0 and ) - then LOG_DEBUG prints: - key pressed.0 code48 - key pressed.) code48

and when i press ; and : then LOG_DEBUG prints: - key pressed.; code186 - key pressed.: code186

Finally: condition

if((key.length==1&&key>='0'&&key<='Z') || ",*-_ ;\'".includes(event.key))

is TRUE for : ; 0 but is FALSE for ) -- why? why? why?

Upvotes: 0

Views: 34

Answers (1)

Herohtar
Herohtar

Reputation: 5613

It returns false for ) because the range you are comparing against doesn't include that character, and you aren't checking for it in your list of extra characters (which also inlcudes some redundant characters). You have a lower bound of '0', which is 48 and an upper bound of Z, which is 90. That range includes the following characters: 0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ

) has a character code of 41.

let chars = ''
let start = '0'.charCodeAt(0)
let end = 'Z'.charCodeAt(0)
console.log(`Starting at: ${start}`)
console.log(`Ending at: ${end}`)
for (let i = start; i <= end; i++)
{
  chars += String.fromCharCode(i)
}
console.log(chars)
console.log(`Value of ')': ${')'.charCodeAt(0)}`)

Upvotes: 1

Related Questions