Comparison of key press and string - javascript

I am doing an experiment and I want a part to be shown if a certain key ("b") is pressed and skipped, if any other key is pressed. The key that is pressed is saved in key_resp_3.keys and if I visualize what's saved in the key_resp_3.keys variable it's simply b.
So I thought this would be the right comparison:
if ((key_resp_3.keys != "b")) {
continueRoutine = false;
}
However in this case, the routine is always skipped so somehow "b" is obviously not the way the key is saved in the key_resp_3.keys variable. Does anyone have an idea what is the right comparison instead?
Thank you!

Hard to tell the root cause of the problem without the rest of the code. But you can simply use an event listener like below
document.addEventListener('keydown', function(event) {
console.log(event.key)
const key = event.key
if(key == "b")
alert("b presed")
});
Or can it be as simple as you are trying to set const key_resp_3 = event.key then checking in the if key_resp_3.keys so you are trying to access variable.key.key
In this special case:
since the keys is a array you can use
Does contains b
key_resp_3.keys.includes('b')
Does not contains b
!key_resp_3.keys.includes('b')

Related

How To Detect Two Characters (Keys) Pressed At The Same TIme

An important distinction is that it is easier to know if cntrl and z are pressed at the same time, but not as straight forward to detect if z and x are pressed at the same time. What is the best way to go about detecting when multiple characters are pressed at the same time?
This example uses event listeners to keep track of an object which contains all keys currently being pressed.
We can use this object to check if certain keys are pressed. This means that we can detect as many simultaneous key presses as a user's keyboard will allow.
Importantly it will let you detect when multiple characters are pressed at the same time.
const keysPressed = {};
document.addEventListener('keydown', (event) => {
if (!event.repeat)
keysPressed[event.key] = true;
//You can also include event.repeat as a condition in your cases if you wish an event to only occur once each trigger.
//You can also include Object.keys(keysPressed).length === 2 (for example) if you only wish the case to be valid if just two keys are pressed.
//Finally, instead of event.key === 'x' you can write keysPressed['x']. This would replace both non-default cases in the example. The result is that the event will continue firing if another key is pressed.
switch (true) { //You use true here because we are using logic to determine each case
case event.key === 'x' && keysPressed['z']:
case event.key === 'z' && keysPressed['x']:
console.log('Z and X pressed!');
break;
default:
break;
}
});
document.addEventListener('keyup', (event) => {
if (!event.repeat)
delete keysPressed[event.key];
});
I'm simply using an array as storage for all keys that are pressed. This array is cleaned to an empty state when keys are released.
In keydown event listener, you can hook the function with logic that you will want to implement. Read keys array to check all currently pressed keys.
const keys = []
document.addEventListener('keydown', e => {
!event.repeat && keys.push(e.key)
doSomethingWithKeys(keys)
})
document.addEventListener('keyup', e => {
keys.splice(0, keys.length)
})
function doSomethingWithKeys(keys) {
console.log('keys pressed:', keys.join('+'))
}

How can I access the result of this function on this other function?

So i have this text input field and I have the showKeyCode() function which gets the value from the text input and prints the keycode representation of the pressed key into the console.
function showKeyCode() {
$('#inputfield').keyup(function(e){
$(this).val(String.fromCharCode(e.keyCode));
console.log(e.keyCode);
});
}
const r4 = document.querySelector("#inputfield");
r4.addEventListener('input', showKeyCode2);
Now i want to get this value and use it at the function below.
$(document).keydown(function(e) {
if (e.which == [I WANT TO PUT THE RESULT FROM showKeyCode() HERE] ){
document.querySelector('#test').click()
console.log("Clicked");
}
});
Lets summarize what I'm trying to do here. If you are a gamer you must have used the keybinds for example : Press [M] to show minimap. Press [H] to show hud.
Here im trying to make the user customize the keybind by typing it into the text field. The showKeyCode() function gets the Character and converts it into a keycode which ill use in the second function.
I couldve typed the keycode directly into the script like this
if (e.which == 84 ){}
but i wanted the user to change it inside the game.
Technically "You can't" But there's a hacky and dirty workaround. Global variables.
//outside
let value = '';
function showKeyCode() {
$('#inputfield').keyup(function(e){
$(this).val(String.fromCharCode(e.keyCode));
value = e.keyCode;
});
}
$(document).keydown(function(e) {
if (e.which == [value] ){
document.querySelector('#test').click()
console.log("Clicked");
}
});
This should work if sowKeyCode was called before a keydown was made
Now, I DO NOT RECCOMMEND using global variables but sometimes its the only way on the approach, perhaps you can use a different method like putting this inside a class or using other libraries that are great with state tracking.

Handling multiple keys pressed at once in JavaScript

For context: this is a JavaScript app running in the Xbox One. All of this is happening through the Xbox's virtual keyboard. Keep in mind that since I have figured out how the events are being fired, this shouldn't matter anymore, just how to deal with the two events at once.
It's not really multiple keys, what is happening is when I turn on CAPS for my app, I am getting two events keys at once: shift and whatever key I am actually pressing. The problem this is causing is that shift seems to be overriding whatever I am trying to spell, and no key is displayed in my input boxes.
I currently have a global function which takes care of all special events in the app, and I would like to handle this issue from over there but am not sure how to go about this issue.
Here is what I currently have:
// this is the global function where I would like to solve the issue
onStartup(function () {
var $html = $('html')
$html.on('keydown', function (evt) {
if (evt.isDefaultPrevented()) return
console.warn('key being pressed:', evt.keyCode)
if (evt.keyCode === 16) { // Note: 16 is shift's keycode
// do something to prevent shift from overriding the actual key I want to press.
return
}
})
})
When I press a key without CAPS being turned on, say a, which has the keyCode of 65, we have the following output:
key being pressed: 65
If however I try to do a capital a (or A), this is what happens:
key being pressed: 16
key being pressed: 65
What can I do to stop the shift from preventing me from actually typing the capital keys?
I figured it out! All I had to do was when shift was fired, to call evt.stopImmediatePropagation().
So basically, for my code:
// ...
if (keycodeControls.is('shift', evt)) {
evt.stopImmediatePropagation()
}

Jquery detect input focus

I am creating a conversion web app to teach myself Javascript. The user can input data with a number pad (basically a calculator without the operators). I also set up a function to detect keystrokes (1-9) which insert data just like the number pad. And also character 'c' which clears all data
My problem is that I also have a search field (which uses auto complete to enable the user to search for other conversions). I dont' want the user to search for something using the 'c' or number keys, and have it enter data into both the number pad, and search field.
My idea was to create a if statement to determine if the search field was active (focused), and if it was to change a variable (enabled) to false, thus disabling the keystroke detection.
The problem I am having is that the function holding the if statement with the focus attribute is not working.
If my rambling made no sense hopefully the code will clear things up.
Here is the if statement with the focus attribute
$(document).ready(function(){
if($(':focus').attr('#searchInput') == 'input')){
enabled === false;
}
});
Here is the code for key stroke detections (I omitted the redundant parts to save space
document.onkeydown = function(event){
var key = event.charCode || event.keyCode;
if(enabled === true){
if(key === 67){
clearInput(input); //Clears form input (input is my form ID)
}else if(key === 48){
writeInput(input, zero); //Zero is a var equaling 0
}
...
}else{
return false; //if enabled is false don't detect keystrokes
}
};
Any help would be greatly appreciated. If anything doesn't make sense I will be happy to explain (or edit the post.)
$(document).keyup(function(e){
if($('#searchInput').is(':focus')) {
return ; // search field is focused, ignore other part of function
}
var key = e.which;
// do your code here
});

Keyboard Number Line vs Keypad Numbers

I'm using Javascript, I need to get the keypad numbers. For what ever reason, my code treats them differently.
function getKey(keyStroke) {
var keyCode = (document.layers) ? keyStroke.which : event.keyCode;
var keyString = String.fromCharCode(keyCode).toLowerCase();
if (lop.charAt(cpos)==keyString) {
document.getElementById("pimachine_e").innerHTML=document.getElementById("pimachine_e").innerHTML+keyString;
cpos++;
} else {
lose();
}
}
The number line at the top of the keyboard acts like expected but the Numberpad is treated (when I click 1) as if I haven't clicked 1. What is it changing it to? How do I get these key presses correctly.
http://www.cambiaresearch.com/c4/702b8cd1-e5b0-42e6-83ac-25f0306e3e25/Javascript-Char-Codes-Key-Codes.aspx
That shows a list with all of the keys on a regular keyboard and the keycodes that are associated with it. As you can see, when pressing 'numpad 1', it should return '97' in this line:
var keyCode = (document.layers) ? keyStroke.which : event.keyCode;
Maybe you can put an alert after that line to check if the variable 'keyCode' has ben filled correctly?
If that doesn't help you along your way, please provide more code, cause I cannot recreate your situation locally because your function is referring to other pieces of code that are not provided. Also, I can't see how this function is being called and how the variable 'keyStroke' is filled.

Categories

Resources