Keyboard Number Line vs Keypad Numbers - javascript

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.

Related

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()
}

JS String has length n, but only n-1 characters. Using str = str.slice(0,-1)

I am using Khan Academy's webpage in order to make a javascript project (which you can see here). I brought that up because I don't know if the problem is due to a subtlety of javascript, or if it is due to Khan Academy's system.
Here is a description of the problem:
var keyPressed = function() {
if (keyCode === BACKSPACE) {
debug(textBuffer.length);
debug(textBuffer);
textBuffer = textBuffer.slice(0,-1);
}
};
This code will, essentially, be run whenever I press the backspace key. When I invoke the code the first time, it works fine; the last character is removed from my global variable textBuffer. However, any subsequent calls to this code do nothing to my textBuffer string, unless textBuffer was changed in between calls. By using debug statements, I have noticed that the string length appears to be one too big.
I hope I have provided enough details for someone to sniff out the problem. Does anyone what is going on?
EDIT: Here is the source of the problem: although keyPressed is correctly registering the backspace, there is another function called keyTyped that was adding an invisible '\b' character into the string. This was how the string appeared to have only 2 characters but a length of 3.
When you press the backspace key, both the keyTyped and keyPressed functions are executed. keyPressed is executed first, which removes a character, and then keyTyped is executed, and adds a character to the string, the backspace character.
In JavaScript, this backspace character actually has an escape character for strings: '\b'.
To fix your problem, handle the backspace key in the keyTyped function, and don't let it append the toString value to the textBuffer.
var keyTyped = function() {
if (key.toString() === '\n') {
parse();
textBuffer = "";
}
if (key.toString() === '\b') {
textBuffer = textBuffer.slice(0, -1);
} else {
textBuffer = textBuffer + key.toString();
}
};

Binding the "onselect" event to a function, that handles the maximum chars. inside an input text field

I am working on a function to limit the number of chars. a user is allowed to type inside an input text field.
This is it:
$.fn.restringLength = function (id, maxLen) {
$(id).keypress(function(e){
var kCode = e.keyCode ? e.keyCode : e.which,
len = $(id).val().length;
if (kCode != 8 && kCode != 46) {
if (len > maxLen) e.preventDefault();
}
});
}
The function binds the keypress event and gets the code of the pushed key.
If the char. limit is reached, it allows only the delete and backspace keys to be pushed.
What it needs to work great, is a way to bind the "onselect" event in order to have the following behavior:
when the user selects the whole text with the mouse, and types a letter or a number, the whole text gets deleted and that letter appears.
This is something that most of us do when we want to replace some text with another, and I'd like my function to enable this.
Any ideas how?
If i may add something,
Your solution use keypress event, so the event is triggered before the new value of input is computed. That's why you have to check for special key like backspace , enter ... theses do not just add a character to the string so they require special treatment.
For this kind of processing, it's more convinient to have the handler triggered after the string computation. In that way, you can access the input value and modify it if it's not correct.
Unfortunately jquery does not support this event but you can use it with vanilla javascript method.
$(id)[0] // get the vanilla js element
.oninput = function(e){
this.value = this.value.substr( 0 , 10 ) // this.value contain the string after the key press processing
}

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
});

Categories

Resources