jQuery keypress array password - javascript

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/

Related

Move player javascript

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.

Change character when keydown is held

I am trying to make a simple way to change a character in an input field when the key is held down for more than 1second. For example holding down a would then change the character to á.
The exact thing I am looking to do can be seen on fluencia.com.
Also there is a need to be able to change the character if it is held for a further second.
So far, all I have done is detect the key held with the following code:
count = 0;
$(document).bind('keypress', function(e){
keyisdown = false;
key = e.which
if (e.which === key) {
keyisdown = true;
count ++;
if(count>1){
}
}
}).bind('keyup',function(){
keyisdown = false;
count = 0;
console.log('key up');
});
Thanks
Adam
This should do it for key "a".. You'll need to look up your keycode
var fired = false;
$(document).on("keydown", function(e) {
if (e.keyCode == 65) {
var timer = setTimeout(function() {
if (!fired) console.log('its held');
fired = true;
}, 1000);
$(document).on("keyup", function() {
clearTimeout(timer);
});
}
});
fiddle - http://jsfiddle.net/0a9rftt2/
With help from Graham T above and a bit of playing around I come up with the following:
var fired = false;
var keycode = null;
var key = null;
$("#loginEmail").on("keypress", function(e) {
keycode = e.which;
key = String.fromCharCode(keycode);
});
$("#loginEmail").on("keydown", function(e) {
var s = this.value;
var str = this.value;
if (e.keyCode == 65) {
var timer = setTimeout(function() {
if (!fired) console.log('its held');
fired = true;
if(fired){
s = $("#loginEmail").val();
str = s.substring(0, s.length - 1);
replacewith = 'á';
str = str+replacewith;
$("#loginEmail").val(str);
}
}, 500);
$(document).on("keyup", function() {
clearTimeout(timer);
fired = false;
});
}
});
It is not cleaned up as yet. I had to use keypress to get the true character (capitalised or not) and then used keydown to detect key being held down.

How to know which key was held when left mouse button was clicked?

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

How to record reaction time if event is not happening jquery/javascript?

I have my function that records the reaction time from the display of the stimulus (word or picture) until the keypress.
But if there is no key pressed, the reaction time will be NaN, yet I'd like it to run through until the next stimulus appears (here after 1000ms), so that the reaction even if no key is pressed is then equal to 1000ms:
How could I record the milliseconds until 1000ms if there is no keypress event?
var t1;
var i = 0;
$(function(){
var timeout = 0;
function showNext() {
t1 = (new Date()).getTime();
if(Math.random() < 0.5) {
var new_word = stim[Math.floor((Math.random()*stim.length)+1)].name;
$("#abc").text(new_word);
} else {
var new_img = stim[Math.floor((Math.random()*stim.length)+1)].path;
$("#abc").empty();
var prox_img = $('<img id="abcimg" height="300px" width="300px">');
prox_img.attr('src', new_img);
prox_img.appendTo('#abc');
}
timeout = setTimeout(function(){showNext()}, 1000);
}
$(document).keypress(function(e){
if ($(e.target).is('input, textarea') || i > 10) {
return;
};
i++;
clearTimeout(timeout);
if (e.which === 97 || e.which === 108 || e.which === 32) {
setTimeout(function(){showNext();}, 100);
var t2 = (new Date()).getTime();
var reac_time = t2-t1;
$("#time").text(reac_time);
}
});
});
At the start of showNext(), just check if the displayed time is NaN, and set it to 1000.
function showNext() {
if( isNaN($("#time").text()) ){
$("#time").text("1000");
}
//... your other code
}
See w3Schools isNaN()

Capturing gamepad input key events in Wii-U web browser

The Internet Browser - Extended Functionality page for the Wii-U browser indicates that the A button and the control pad should send key events to the browser. Using the sample code below I was able to receive events for the A button but the directional pad seems to just want to scroll around the page and no events are triggered.
How can I properly receive notification of these events?
<script>
document.body.onkeypress = function (event) {
var pad = ["LEFT", "UP", "RIGHT", "DOWN"];
var div = document.getElementById("text");
// handle the A button
if (event.keyCode == 13) {
div.innerText = "A";
}
// handle the control pad - this doesn't seem to work
if (event.keyCode >= 37 && event.keyCode <= 40) {
div.innerText = pad[event.keyCode - 37];
}
};
</script>
I would rather avoid polling the window.wiiu.gamepad object as I only need the input that should be provided through the Control Pad and A button key events.
Turns out the A button can be captured by any of the the keydown, keyup or keypress events but the eight way digital pad can only be captured through the keydown and keyup events. You can also cancel the event to prevent the normal browser handling of moving between links on a page with preventDefault().
Sample code:
document.body.onkeyup = function (event) {
var pad = ["LEFT", "UP", "RIGHT", "DOWN"];
var div = document.getElementById("text");
// handle the A button
if (event.keyCode == 13) {
div.innerText = "A - KEYUP";
}
// handle the control pad
if (event.keyCode >= 37 && event.keyCode <= 40) {
div.innerText = pad[event.keyCode - 37] + " - KEYUP";
}
// prevent the Wii U browser from processing the event further
event.preventDefault();
return false;
};
document.body.onkeydown = function (event) {
var pad = ["LEFT", "UP", "RIGHT", "DOWN"];
var div = document.getElementById("text");
// handle the A button
if (event.keyCode == 13) {
div.innerText = "A - KEYDOWN";
}
// handle the control pad
if (event.keyCode >= 37 && event.keyCode <= 40) {
div.innerText = pad[event.keyCode - 37] + " - KEYDOWN";
}
// prevent the Wii U browser from processing the event further
event.preventDefault();
return false;
};
document.body.onkeypress = function (event) {
var div = document.getElementById("text");
// handle the A button
if (event.keyCode == 13) {
div.innerText = "A";
}
};

Categories