I do not understand this part :
self.keyDown = function() { keys[event.keyCode] = 1; };
self.keyUp = function() { delete (keys[event.keyCode]); };
explain what this code does, please)
MVC :
Controller:
this.init = function() {
keys = {};
}
self.trgt = function(){
if(this.event.target === myContainer.querySelector('#start')) {
myModel.startGame();
window.addEventListener('keydown', self.keyDown);
window.addEventListener('keyup', self.keyUp);
}
}
self.keyDown = function() {
keys[event.keyCode] = 1;
};
self.keyUp = function() {
delete (keys[event.keyCode]);
};
self.moveHero = function(keycode) {
myModel.moveHero(keycode);
};
setInterval(function() {
for (let keycode in keys) {
self.move(keycode);
}
}, 20);
Model:
if (!sometask) {
if (keycode == 37 || keycode == 65) {
self.moveLeft();
}
if (keycode == 38 || keycode == 87) {
self.moveTop();
}
if (keycode == 39 || keycode == 68) {
self.moveRight();
}
if (keycode == 40 || keycode == 83) {
self.moveBottom();
}
}
};
the code in question:
self.keyDown = function() { keys[event.keyCode] = 1; };
self.keyUp = function() { delete (keys[event.keyCode]); };
is just assigning which keys are currently pressed. Lets say event.keyCode = 37, In this instance your keys variable, which is an object, will now have a property that says keys[37] = 1, and it will remain that way until the keyUp function is called, deleting it. Whiile keys[37] = 1, the character will continue moving left, and this will stop once that key is deleted.
self.keyDown = function() { keys[event.keyCode] = 1; };
self.keyUp = function() { delete (keys[event.keyCode]); };
Translating to plain English:
If the user press the keyDown (number 40) then set the key 40 in the object keys to 1.
If the user press the keyUp (number 38) then delete from the keys object the key 38
These lines are to set functions that will be called each time the event keyDown (press a key) or keyUp (release the key) are called.
So let's focus on the actual code inside the function :
for keyDown, it sets a variable in a dictionary to a value. for instance, if you press down 'a', 'a' key on the keyboard has some int value which is 65 (see https://keycode.info/), and it will set the keys[65] = 1.
As long as you keep the button press, this value will stay, but as soon as you release it, the value is unset by using delete .
And so on for each keyboard key.
Then the main loop of the game will look which variables are set (by using "for ... in keys), and will execute a move function for each variable that has a special values, corresponding, I guess, to a-w-s-d or left-up-right-down.
Related
I want to check the value of a input field against a value in my js object on pressing enter. the if (document.getElementById("barcode").value === element.anr) works. however, i only want it to execute document.getElementById("next").click(); if barcodecounter is equal to element.menge.
Basically if element.menge has a value of 5, the first time document.getElementById("barcode").value is equal to element.anr I want barcodecounter to increase by 1 and when its equal to element.menge it should execute document.getElementById("next").click();.
Currently if e.g. element.menge is 5, it still executes document.getElementById("next").click(); even when I only provided it once instead of 5 times.
What am I doing wrong?
document.getElementById("barcode").addEventListener("keypress", function(e) {
let barcodecounter;
if (event.which == 13 || event.keyCode == 13) {
if (document.getElementById("barcode").value === element.anr) {
barcodecounter++;
if (barcodecounter = element.menge) {
document.getElementById("next").click();
}
console.log(document.getElementById("barcode").value, element.anr);
console.log(element.menge);
}
else if (document.getElementById("barcode").value != element.anr){
alert("Falscher Artikel");
}
}
});
You are using an assignment = not a boolean compare ==, simple change. I also added some adjustments to the code to initialize stuff. element might be something else but was not in there
// used this but not declared:
//let element = {};
//element.anr = 0;
//element.menge = 0;
//OR use, I assume numerics heres
let element = {
anr: 0,
menge: 0
};
document.getElementById("barcode").addEventListener("keypress", function(e) {
let barcodecounter = 0;// set initial value;
if (event.which == 13 || event.keyCode == 13) {
if (document.getElementById("barcode").value === element.anr) {
barcodecounter++;
if (barcodecounter == element.menge) {
document.getElementById("next").click();
}
console.log(document.getElementById("barcode").value, element.anr);
console.log(element.menge);
} else /* no need for else if here */ {
alert("Falscher Artikel");
}
}
});
I have used a function which is activated on click events. I want to do the same using keypress events.
function addToText(target) {
var exp = target.target;
//alert(exp.value);
if (newExp) {
//clearText();
document.getElementById("expression").value = exp.value;
newExp=false;
}
else
document.getElementById("expression").value = document.getElementById("expression").value + exp.value;
}
This is the function used. How do I modify it to use for keypress events also. Currently, it does not work initially(for keypress events). But after clicking once, then any keypress returns the same number that was previously clicked.
Full code here:http://codepen.io/jpninanjohn/pen/JXVpYb?editors=1010
Here's is your final solution, I test if charcode is between 48 and 57, what it means, numbers between 0 and 9.
document.addEventListener('keypress', function(e){
if (e.which >= 48 && e.which <= 57)
document.getElementById("expression").value+= String.fromCharCode(e.which);
});
You can use this function-
window.onkeyup = function(e) {
var key = e.keyCode ? e.keyCode : e.which;
document.getElementById("expression").value += key-48; //for getting the number
alert(key);
if (key == 38) {
//whatever
}else if (key == 40) {
// whatever
}
}
source
And you need to add + to the =
document.getElementById("expression").value+=
instead of -
document.getElementById("expression").value=
You have to add a different function for keyPress event, because the keypress event get the value of pressed key differently, not target.target
function addToTextKeypress(event) {
var exp = String.fromCharCode(event.keyCode);
//alert(exp);
if (newExp) {
//clearText();
document.getElementById("expression").value = exp;
newExp=false;
}
else
document.getElementById("expression").value = document.getElementById("expression").value + exp;
}
Later you need to remove exp.value since it has the direct value
The title says most of it. I'd like a javascript/html solution for how to make persistent, user-configurable keyboard shortcut listeners (plus any nice thoughts on how to actually persist the preferences if you have 'em).
It seems both straightforward and slightly tricky at the same time :)
Thanks!
If you want to allow the user get shortcuts like "Control"+(...), you just have to capture the keys pressed, so check if "Control" is pressed with such keys pressed to do an action.
This is an simple and bad example of doing this:
var Pressed={
CTRL:false,
Spacebar:false
},Keyboard={ // an object containing Keyboard keys code
CTRL:17,
Spacebar:32
};
window.onkeydown=function(e){ // user started pressing an key (event)
var Key=(e.keyCode||e.which||e.key); // capture key pressed from event
if(Key==Keyboard.CTRL){ // CTRL is pressed
Pressed.CTRL=true
Pressed.Spacebar=false // CTRL has to be pressed before than Spacebar
}else if(Key==Keyboard.Spacebar){ // Spacebar is pressed
Pressed.Spacebar=true
}
if(Pressed.CTRL&&Pressed.Spacebar){ // Case CTRL+Spacebar are pressed
e.preventDefault(); // prevent Opera from quitting from the page
console.log("CTRL+Spacebar were pressed.")
}
},
window.onkeyup=function(e){ // event when an key is released
var Key=(e.keyCode||e.which||e.key); // capture key released from event
if(Key==Keyboard.CTRL){ // CTRL is released
Pressed.CTRL=false
}else if(Key==Keyboard.Spacebar){ // Spacebar is released
Pressed.Spacebar=false
}
};
To update...
You can try something like this:
For demo purpose, I have just logged if Alt, Ctrl or Shift + 'Key' and if key is defined in shortcuts, then print Special action else 'Normal action'. Also I have disabled propagation of key events for inputs, but this section can be removed if not required.
JSFiddle
Code
(function keyLogger() {
var isCtrlPressed = false;
var isAltPressed = false;
var isShiftPressed = false;
var shortcutKeys = [
13, // Enter
32, // Space
37, // Left Arrow
38, // Up Arrow
39, // Right Arrow
40, // Down Arrow
90, // z
]
function registerEvents() {
document.onkeydown = function(event) {
var keyCode = event.keyCode ? event.keyCode : event.which;
if (keyCode >= 16 && keyCode <= 18) {
updateKeyFlags(keyCode, true);
}
if (isCtrlPressed || isAltPressed || isShiftPressed) {
if (shortcutKeys.indexOf(keyCode) >= 0) {
console.log("Special action");
} else {
console.log("Normal action");
}
}
}
document.onkeyup = function(event) {
var keyCode = event.keyCode ? event.keyCode : event.which;
if (keyCode >= 16 && keyCode <= 18) {
updateKeyFlags(keyCode, false);
}
}
// To prevent logging from Inputs.
// Can be removed if this action is required.
var inputs = document.getElementsByTagName("input");
for (var i in inputs) {
inputs[i].onkeyup = function(event) {
event.stopPropagation();
}
inputs[i].onkeydown = function(event) {
event.stopPropagation();
}
}
}
function updateKeyFlags(keyCode, flag) {
switch (keyCode) {
case 16:
isShiftPressed = flag;
break;
case 17:
isCtrlPressed = flag;
break;
case 18:
isAltPressed = flag;
break;
}
}
registerEvents();
})();
<div>
<input type="text">
<input type="text">
</div>
I wan't to detect if some other key is held when the left mouse button is clicked how can i do it?
i used this to detect ctrl+shift but now i wan't to know if 'A' or 'B' or both were held.
if(e.shiftKey && e.ctrlKey) console.log("ctrl+shift key was held when pressing the left mouse button");
the mouse event I receive doesn't have a keyCode for held keys. I want pure Javascript.
Maybe something like this (listening for keydown and keyup):
var keys = [];
$(document).keydown(function(e){
var index = keys.indexOf(e.keyCode);
if(index === -1){
keys.push(e.keyCode);
}
}).keyup(function(e){
var index = keys.indexOf(e.keyCode);
if(index !== -1){
keys.splice(index, 1);
}
}).click(function(e){
console.log(keys);
});
A pure javascript solution would be:
var held_key = null;
function key_down(event) {
var key = event.keyCode || event.which;
// get string representation of held key
var keychar = String.fromCharCode(key);
// store held key in global variable
held_key = keychar;
}
//revert held_key to null onkeyup
function key_up(event) {
var key = event.keyCode || event.which;
held_key = null;
}
window.onload = function() {
window.onkeydown = key_down;
window.onkeyup = key_up;
window.onclick = function(e) {
// put condition for the key you want here
if (held_key == 'A') {
//do something
console.log('hi!');
}
}
}
I'm wondering how to record keypresses on a blank html page, like, if A->B->C keys are pressed in a row (after eachother), then display a div or redirect the user. And if the user presses A->B-> but not C, then reset the array so the user has got to type it in again (from the start) in order for the desired action to be triggered.
Just a rough example
var checkArray = [],
error = 'Enter the right combination !!',
success = 'Success !!',
$div = $('#div'),
timer = 1000,
timeout;
$(document).on('keyup', function (e) {
if(timeout) clearTimeout(timeout);
var keyPressed = e.keyCode;
(keyPressed > 64 && keyPressed < 68) ? checkArray.push(keyPressed)
: checkArray = [];
console.log(checkArray.join('-'));
if (checkArray && checkArray.length === 3) {
if (checkArray[0] === 65 && checkArray[1] === 66
&& checkArray[2] === 67) {
$div.text(success).addClass('a');
timer = 2000;
}
} else {
$div.text(error).removeClass('a');
}
timeout = setTimeout(reset, timer);
});
function reset() {
timer =1000;
checkArray = [];
$div.text(error).removeClass('a');
}
Check Fiddle
capture the keydown events and store the results in global variables. put logic in the capture event to do the desired action.
See http://api.jquery.com/keydown/