Javascript fromCharCode keyCode - javascript

I need the keycodes for something but I don't know what kind of keycode it is, I couldn't find it anywhere else.
function keyDown(e) {
if (String.fromCharCode(e.keyCode) == "%") isLeft = true;
if (String.fromCharCode(e.keyCode) == "'") isRight = true;
}
function keyUp(e) {
if (String.fromCharCode(e.keyCode) == "%") isLeft = false;
if (String.fromCharCode(e.keyCode) == "'") isRight = false;
}
I figured out that % is left arrow and ' is the right arrow, could anyone tell me what kind of keycode thingy this is? or maybe how I could change it to a better one.
Thanks :)

You can easily find keycode values by googling for "javascript keycodes", or just use this website: keycode.info
The keycode for left arrow is 37, right arrow is 39.
In your code you converted e.keyCode to an ASCII character, which is unnecessary. Unsurprisingly, ASCII character #37 is %, #39 is '.
Just compare the keycode values directly:
function keyDown(e) {
if (e.keyCode == 37) isLeft = true;
if (e.keyCode == 39) isRight = true;
}
function keyUp(e) {
if (e.keyCode == 37) isLeft = false;
if (e.keyCode == 39) isRight = false;
}

You could use e.key, it returns value of the pressed key. So if you press left arrow key e.key would be "ArrowLeft" and if you press right arrow key e.key would be "ArrowRight".

You can lookup these codes Keycode table
or
check them interactively here: http://keycode.info/ or http://keycodes.atjayjo.com/
The function String.fromCharCode will then convert a unicode number into a character.
For cross browser compatibility you might want to check both the e.which and e.keyCode properties like below.
function(e) {
e = e || window.event;
var keyCode= e.which || e.keyCode;
var charStr = String.fromCharCode(keyCode);
alert("The keycode is: "+ keyCode + " and charCode is: " + charStr);
}

You don't need to get the character for those key codes, you could just compare them directly:
function keyDown(e) {
if (e.keyCode === 37) isLeft = true;
if (e.keyCode === 39) isRight = true;
}
function keyUp(e) {
if (e.keyCode === 37) isLeft = false;
if (e.keyCode === 39) isRight = false;
}
Anyway, keep in mind e.keyCode is deprecated, so e.key or e.code should be used instead, which also makes the code easier to understand. Also, you could use an object with boolean properties instead of individual booleans to make this scale better to more keys:
const pressedKeys = {};
document.onkeydown = ({ key }) => {
pressedKeys[key] = true;
console.log(Object.keys(pressedKeys).join(' + '));
};
document.onkeyup = ({ key }) => {
delete pressedKeys[key];
console.log(Object.keys(pressedKeys).join(' + '));
};
Just keep in mind some old browsers used non-standard codes, so left is usually 'LeftArrow ' and right is 'RightArrow', but on IE it's just 'Left' and 'Right' instead.
Also, if you need to check KeyboardEvent's properties values such as e.key, e.code, e.which or e.keyCode you can use https://keyjs.dev. I will add information about these kinds of cross-browser incompatibilities soon!
Disclaimer: I'm the author.

Related

p5.js: how can I limit keyPressed to sending just 1 output?

I'm trying to prevent players from pressing both left and right keys at the same time, since doing so will change both "isLeft" and "isRight" to true. I've tried the code below but it makes the controls really stiff, for example, if you were to let go of "D" too late before pushing "A", it will register "D" being released but would not register "A" being pressed (since A is pressed when "isRight" is true. Sorry if this analogy is too confusing...
I'm looking for a way to take input from pressing "A", and if "D" is still pressed after "A" is released, immediately take input from "D".
Thanks in advance!
function keyPressed()
{
if ((key == 'A' || keyCode == 37) && !isRight)
{
isLeft = true;
}
else if ((key == 'D' || keyCode == 39) && !isLeft)
{
isRight = true;
}
}
A solution to interpret left vs right when both keys are pressed is to listen for keyPressed and keyReleased. On keyReleased we can also check and see if the alternate key is already down. This approach allows the code to immeditally switch to the other key when both are down and one is released
var isLeft = false;
var isRight = false;
function setup(){
frameRate(10);
}
function keyPressed(){
if ((key == 'A' || keyCode == 37) && !isRight){
isLeft = true;
} else if ((key == 'D' || keyCode == 39) && !isLeft) {
isRight = true;
}
}
function keyReleased(){
if ((key == 'A' || keyCode == 37)){
isLeft = false;
if ((keyIsDown(16) && keyIsDown(68)) || keyIsDown(39)){
isRight = true;
}
}
else if ((key == 'D' || keyCode == 39)){
isRight = false;
if ((keyIsDown(16) && keyIsDown(65))|| keyIsDown(37)){
isLeft = true;
}
}
}
function draw(){
console.log( " isLeft: "+isLeft + " isRight: " + isRight);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.min.js"></script>
The keyIsDown detects if a key is being pressed. I'm not sure if it works for all characters, but it works for the arrow keys. If you add !keyIsDown(RIGHT_ARROW), then it sees if the Right arrow is down. If it's down, then the if isn't true, if it's false the if is true it's being run.
Tell me if this doesn't work.
function keyPressed()
{
if ((key == 'A' || keyCode == 37) && !isRight&&!keyIsDown(RIGHT_ARROW))
{
isLeft = true;
}
else if ((key == 'D' || keyCode == 39) && !isLeft!keyIsDown(LEFT_ARROW))
{
isRight = true;
}
}

Key down and up events doesn't work in Javascript

document.addEventListener("keydown", keyD);
document.addEventListener("keyup", keyU);
function keyD(e){
if(e.keycode == 38){
plat1UpP = true;
}else if(e.keycode == 40){
plat1DownP = true;
}
}
function keyU(e){
if(e.keycode == 38){
plat1UpP = false;
}else if(e.keycode == 40){
plat1DownP = false;
}
}
I am trying to make a pong game in html5, javascript and css with canvas, but the events for keydown and keyup don't work.
you must change keycode to keyCode.
consider some browsers doesn't support keyCode and you must use
which.
Change your code to this, it will work for all of them.
document.addEventListener("keydown", keyD);
document.addEventListener("keyup", keyU);
function keyD(e){
var key = e.keyCode || e.which;
if(key == 38){
plat1UpP = true;
}else if(key == 40){
plat1DownP = true;
}
}
function keyU(e) {
var key = e.keyCode || e.which;
if(key ){
plat1UpP = false;
}else if(key){
plat1DownP = false;
}
}
You have syntax error, you new to use e.keyCode insted of e.keycode.

Web page change when left or right arrow in keyboard pushed

i want to ask how can i change the web page when the arrow key pushed by user , like a web of manga/book if we want to next page we just push the arrow key
sorry for my english , thanks before
You can use jQuery for that:
$(document).keydown(function(e) {
if (e.which == 37) {
alert("left");
e.preventDefault();
return false;
}
if (e.which == 39) {
alert("right");
e.preventDefault();
return false;
}
});
If you wish to use the jQuery framework, then look at Binding arrow keys in JS/jQuery
In plain javascript, I'll go with :
document.onkeydown = function (e) {
e = e || window.event;
var charCode = (e.charCode) ? e.charCode : e.keyCode;
if (charCode == 37) {
alert('left');
}
else if (charCode == 39) {
alert('right');
}
};
Here is a non jQuery option:
document.onkeydown = arrowChecker;
function arrowChecker(e) {
e = e || window.event;
if (e.keyCode == '37') { //left
document.location.href = "http://stackoverflow.com/";
}
else if (e.keyCode == '39') { //right
document.location.href = "http://google.com/";
}
}

How to allow only numbers in a texbox but also allow entry with French keyboard

I have the following code to allow only numbers to be entered (other logic is removed for brevity).
$("input").keydown(function (event) {
var key = event.keyCode;
if ((key < 48 || key > 57) && (key < 96 || key > 105) || event.shiftKey) {
event.preventDefault();
}
});
This code works fine in English keyboards but on French keyboards the shift key is used so the logic fails there. If i remove the shift the logic fails in english keyboards.
Is there a way to detect a number is being pressed in the keydown event that will work on any type of keyboard?
Thanks
Use a custom function to check if the value of the keydown is numeric. From this previous answer (Validate decimal numbers in JavaScript - IsNumeric()):
function isNumber(n)
{
return !isNaN(parseFloat(n)) && isFinite(n);
}
And your handler UPDATED:
$("input").keydown(function (event) {
var code = event.keyCode;
//Allows left and right arrows, backspace, and delete
if(code == 37 || code == 39 || code == 8 || code == 46)
return;
var character = String.fromCharCode(code);
if(event.shiftKey || !isNumber(character)){
event.preventDefault();
}
});
I have found that event.key works better than event.keyCode. The event handler needs to be onkeydown for it to work properly. The check for whether it's a number needs to come first. Here's my code. Tested to work on IE11, Edge, Chrome, and Firefox.
$("input").keydown(function (event) {
var code = event.keyCode;
var key = event.key;
if (!isNaN(Number(key)))
return;
// allow backspace, delete, left & right arrows, home, end keys
if (code == 8 || code == 46 || code == 37 || code == 39 || code == 36 || code == 35) {
return;
} else {
evt.preventDefault();
}
});
#HostListener('keydown', ['$event']) onKeyDown(event) {
if ((e.keyCode < 48 || e.keyCode > 57) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
} else if (!this.isNumber(e.key)) {//For french keyboard
e.preventDefault();
}
}
}
isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
I had a similar problem because of 2 different keyboards. And I solve that by checking if is not a number in the key value instead of the keyCode value.
Would this work?
$("input").bind("propertychange input textInput", function() {
this.value = this.value.replace(/[^\d.]/g, "");
});
Of course, this trims the value after the input event, so I'm not sure if that's what you want

Working with multiple key press events (windows key)

While working with the multiple keypress events i found this code which worke fine
$(document).bind('keypress', function(event) {
if( event.which === 65 && event.shiftKey ) {
alert('you pressed SHIFT+A');
}
});
But to make it to work wth combinig with windows key... like
event.which === 65 && event.windowsKey
it failed...
Is there any option to make it work with windows key?
if it is a mac machine there is no key as windows..so what could be the alternate option for windows key in mac
Use keyup event.
On a Mac left Command is which = 91, right Command is which = 93. I can't tell what are those on Windows, but you can test it yourself. As #ian commented they should be 91 and 92 respectively.
To test
$(document).on('keyup', function(e) {
var modKey = "";
if (e.shiftKey) modKey += "shiftKey,";
if (e.ctrlKey) modKey += "ctrlKey,";
if (e.altKey) modKey += "altKey,";
if (e.metaKey) modKey += "metaKey,";
console.log ("which: " + e.which + " modkey: " + modKey );
});
UPDATE: Try use keydown event and event.metaKey
$(document).on('keydown', function(e) {
if(e.which === 65 && event.metaKey ) {
console.log ("You pressed Windows + A");
}
});
Remember the key you pressed before. Like if you press shift. get a boolean or something to shiftPressed = true on a onKeyRelease make it false again. That way you can check if shiftPressed == true && aPressed == true before doing something
I made something a while ago for a little WASD game. Perhaps it makes more sense if you see the code:
var up = false;
var down = false;
var left = false;
var right = false;
function keyUp(e) {
keyCode = (e.keyCode ? e.keyCode : e.which);
if (keyCode == 37 || keyCode == 65) {
left = false;
}
if (keyCode == 38 || keyCode == 87) {
up = false;
}
if (keyCode == 39 || keyCode == 68) {
right = false;
}
if (keyCode == 40 || keyCode == 83) {
down = false;
}
}
function forceStopMoving() {
left = false;
up = false;
right = false;
down = false;
}
function keyDown(e) {
keyCode = (e.keyCode ? e.keyCode : e.which);
if (keyCode == 37 || keyCode == 65) {
left = true;
}
if (keyCode == 38 || keyCode == 87) {
up = true;
}
if (keyCode == 39 || keyCode == 68) {
right = true;
}
if (keyCode == 40 || keyCode == 83) {
down = true;
}
}

Categories