Keylistener in Javascript - javascript

I'm looking for a KeyListener for a game I'm developing in JavaScript. I have no idea how this would work in real code but it would be something like this:
if(keyPress == upKey)
{
playerSpriteX += 10;
}
else if(keyPress == downKey)
{
playerSpriteY -= 10;
}
etc...
I searched it up, and Google came up with things that involved AJAX which I don't understand yet. Is there a built in function in JavaScript that does this?

Here's an update for modern browsers in 2019
let playerSpriteX = 0;
document.addEventListener('keyup', (e) => {
if (e.code === "ArrowUp") playerSpriteX += 10
else if (e.code === "ArrowDown") playerSpriteX -= 10
document.getElementById('test').innerHTML = 'playerSpriteX = ' + playerSpriteX;
});
Click on this window to focus it, and hit keys up and down
<br><br><br>
<div id="test">playerSpriteX = 0</div>
Original answer from 2013
window.onkeyup = function(e) {
var key = e.keyCode ? e.keyCode : e.which;
if (key == 38) {
playerSpriteX += 10;
}else if (key == 40) {
playerSpriteX -= 10;
}
}
FIDDLE

The code is
document.addEventListener('keydown', function(event){
alert(event.keyCode);
} );
This return the ascii code of the key. If you need the key representation, use event.key (This will return 'a', 'o', 'Alt'...)

JSFIDDLE DEMO
If you don't want the event to be continuous (if you want the user to have to release the key each time), change onkeydown to onkeyup
window.onkeydown = function (e) {
var code = e.keyCode ? e.keyCode : e.which;
if (code === 38) { //up key
alert('up');
} else if (code === 40) { //down key
alert('down');
}
};

Did you check the small Mousetrap library?
Mousetrap is a simple library for handling keyboard shortcuts in JavaScript.

A bit more readable comparing is done by casting event.key to upper case (I used onkeyup - needed the event to fire once upon each key tap):
window.onkeyup = function(event) {
let key = event.key.toUpperCase();
if ( key == 'W' ) {
// 'W' key is pressed
} else if ( key == 'D' ) {
// 'D' key is pressed
}
}
Each key has it's own code, get it out by outputting value of "key" variable (eg for arrow up key it will be 'ARROWUP' - (casted to uppercase))

Related

Would there be a shorter version of this part of code in JS / CSS / HTML programming?

A question in JS / CSS / HTML programming!
Again, I'm not good at asking the question pinpoint, and sorry for all the confusion. I shall talk about my real intention for this part of code, and see what solutions can be made.
I'd like to invite the users to input characters, which will be thrown into part of the variable characters for another function create_random_string().
If that's the case, what solutions can be made to shorten the code for the part document.addEventListener() for the sake of efficiency? Thank you very much!
var characters = '';
function create_random_string(string){
var random_string = '';
for (var i, i = 0; i < string; i++) {
random_string += characters.charAt(Math.floor(Math.random() * characters.length));
}
return random_string;
}
document.addEventListener('keydown', function(event) {
if(event.key == "a") {
characters += "a";
}
else if(event.key == "b") {
characters += "b";
}
else if(event.key == "c") {
characters += "c";
}
...
else if(event.key == "x") {
characters += "x";
}
else if(event.key == "y") {
characters += "y";
}
else if(event.key == "z") {
characters += "z";
}
Why not check for a range of keys:
document.addEventListener('keydown', function(event) {
if (event.key >= 'a' && event.key <= 'z'){
console.log(event.key);
}
e is Event Object. .key is an Event property that gets the key that was tapped. When testing a key event make sure to click the testing area to gain focus first.
document.onkeydown = logKey;
function logKey(e) {
console.log(e.key);
}
One way to do this that's even shorter than the other answers:
document.onkeydown = (e) => console.log(e.key);
This uses an inline function to further reduce the length of the answer by zer00ne.
If you are more interested in form validation than just logging to the console, you can also do something along the lines of the following:
function alphaOnly(event) {
let key = event.keyCode;
return ((key >= 65 && key <= 90) || key == 8);
};

How to trigger an event when three keyboards are pressed at the same time in Javascript

I'm writing code to execute a specific function when the ctrl + shift + z key is pressed. When I press two keys at the same time, it works fine, but when I press three keys, the event does not occur. Below is the code I wrote.
try1:
document.onkeydown = function (e) {
if (e.ctrlKey && e.key === 'z') { // It works
undo() // ctrl+ z
}
else if (e.ctrlKey && e.shiftKey && e.key==='z' ) { //It doesn't work
redo(); //ctrl + shift + z
}
}
try2:
document.onkeydown = function (e) { //
var ctrl, shift,z
console.log(e.key)
switch (e.key) {
case 'Control':
ctrl = true;
break;
case 'Shift':
shift = true;
break;
case 'Z':
z = true;
break;
}
if (ctrl&&shift&&z) redo()
}
Neither of these will work if you're typing on three keyboards.
How to make it work when ctrl+shift+z is pressed
Change the order of the conditions, as the first condition is always true if the second is true, causing the code for the second condition to never execute.
document.onkeydown = function(e) {
if (e.ctrlKey && e.shiftKey && e.key === 'Z') {
undo()
} else if (e.ctrlKey && e.key === 'Z') {
redo();
}
}
I nice way to keep track of pressed keys is with an object:
const keys = {}
function onKeyDown(e) {
keys[e.key.toLowerCase()] = true
doSomething()
}
function onKeyUp(e) {
keys[e.key.toLowerCase()] = false
}
window.addEventListener('keydown', onKeyDown)
window.addEventListener('keyup', onKeyUp)
function doSomething() {
console.log(keys)
if (keys.control && keys.shift && keys.z) {
console.log("redo!")
} else if (keys.control && keys.z) {
console.log("undo!")
}
}

Tetris on Java Script key control problem

I am having a problem when I move my key controls mainly the arrows on the keyboard. If the viewpoint is small enough it also moves the screen up and down because of the vertical side bar and the tetris piece at the same time. And I want the pieces to only move when I press the arrows. I am a novice at Js and I am not sure where to start to solve the problem, suggestions to where to start to look at?
Here is my Js script
document.addEventListener("keydown", CONTROL);
function CONTROL(event) {
if (event.keyCode == 37) {
p.moveLeft();
dropStart = Date.now();
}
else if (event.keyCode == 38) {
p.rotate();
}
else if (event.keyCode == 39) {
p.moveRight();
dropStart = Date.now();
}
else if (event.keyCode == 40) {
p.moveDown(0);
}
}
Arrow keys moving the browser window is a default browser behavior.
Use event.preventDefault()
To listen only to arrow keys use if (k >= 37 && k <= 40) {, or the opposite: if (k < 37 || k > 40) return;
const p = { // JUST FOR THIS DEMO. You use Piece.prototype
moveLeft() { console.log("LEFT"); },
rotate() { console.log("ROTATE"); },
moveRight() { console.log("RIGHT"); },
moveDown() { console.log("DOWN"); },
};
document.addEventListener("keydown", CONTROL);
function CONTROL(event) {
const k = event.keyCode;
if (k < 37 || k > 40) return; // Do nothing if was not an arrow key. Else Do:
event.preventDefault(); // Prevent browser scroll on arrows
if(k == 37 || k == 39) dropStart = Date.now(); // Only for left or right
return {
37: p.moveLeft,
38: p.rotate,
39: p.moveRight,
40: p.moveDown
}[k]();
}
html, body {min-height: 100%;}
so the problem here is that is that it's sensing each key individually (I've had the same problem so you need a keymap to keep track off ALL the keys pressed like so:
var keys = [];
function keysPressed(e) {
keys[e.keyCode] = true;
}
function keysReleased(e) {
keys[e.keyCode] = false;
}
if(keys[37] === true){
//do stuff here
}
if(keys[38] === true){
//do stuff here
}
You may also want to use the proper identifier "==="

How to set combination of key codes in javascript

I use this code for replacing Enter key with TAB key :
function EnterTab() { if (event.keyCode == 13) event.keyCode = 9; return false; }
I want to know what can I do if I want replace right arrow key with SHIFT + TAB?
if(event.keyCode == 39){
event.shiftKey = true;
event.keyCode = 9;
return false;
}

Javascript/jQuery: Convert key combo to string?

I'm looking for an existing Javascript library, or even better, a jQuery plugin, which detects a key combo and outputs the corresponding string (for example, "ctrl+shift+f"). This is to allow a user to configure a key combo for a Google Chrome plugin. The preferences behavior for BetterTouchTool ( http://www.boastr.de/ ) is a good example of what I'm talking about. Has anyone come across something like this?
I think something of this kind might help:
document.onkeydown = KeyDownHandler;
document.onkeyup = KeyUpHandler;
var CTRL = false;
var SHIFT = false;
var ALT = false;
var CHAR_CODE = -1;
function KeyDownHandler(e) {
var x = '';
if (document.all) {
var evnt = window.event;
x = evnt.keyCode;
}
else {
x = e.keyCode;
}
DetectKeys(x, true);
DoSometing();
}
function KeyUpHandler(e) {
var x = '';
if (document.all) {
var evnt = window.event;
x = evnt.keyCode;
}
else {
x = e.keyCode;
}
DetectKeys(x, false);
DoSometing();
}
function DetectKeys(KeyCode, IsKeyDown) {
if (KeyCode == '16') {
SHIFT = IsKeyDown;
}
else if (KeyCode == '17') {
CTRL = IsKeyDown;
}
else if (KeyCode == '18') {
ALT = IsKeyDown;
}
else {
if(IsKeyDown)
CHAR_CODE = KeyCode;
else
CHAR_CODE = -1;
}
}
function DoSometing() {
//check for keys here
}
I hope it'll be useful
$(document).keypress(function(e) {
alert(
(e.ctrlKey ? 'ctrl+' : '') +
(e.altKey ? 'alt+' : '') +
(e.shiftKey ? 'shift+' : '') +
String.fromCharCode(e.which).toLowerCase()
);
});
This will register the keys; not sure how you're going to block the ctrl/alt keys from getting interpreted though.
browser support: http://www.quirksmode.org/js/keys.html
I forgot I even asked this question! After many months, I've written a plugin myself that does exactly this =)
http://suan.github.com/jquery-keycombinator/

Categories

Resources