Changing variable after keypress? - javascript

I'm trying to make a fun little game.
You have to press all the keys on the screen as fast as you can, without getting it wrong.
But struggling to change the variable after the first keypress. This is what I have:
<script language="JavaScript">
document.onkeydown = checkKeycode;
var uyhgg=13;
function checkKeycode(e) {
var keycode;
if (window.event) {
keycode = window.event.keyCode;
} else if (e) {
keycode = e.which;
}
if (keycode == uyhgg){
document.write(keycode);
} else {
alert("you hit the wrong key");
}
}
</script>
Now after document.write(keycode); I want it to change the variable uyhgg (key code) to something else. 13 is enter.

A call to document.write() after your page loads will obliterate the page. Instead of that, I suggest you make the code update some page element.
if (keycode == uyhgg){
document.getElementById("something").innerHTML = keycode;
}
Put a <div> or <span> or whatever somewhere on the page with that "id" value:
<div id='something'>your keycode will go here</div>
As for changing the variable, well, you should be able to just change it.
uyhgg = 32;
or whatever you need to change it according to, well, whatever the game needs.

Uhmm ... you simply assign it?
document.onkeydown = checkKeycode;
var uyhgg=13;
function checkKeycode(e) {
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
if (keycode == uyhgg){
document.write(keycode);
uyhgg = 27;
alertUyhgg();
}
else {
alert("you hit the wrong key");
}
}
function alertUyhgg() {
alert(uyhgg);
}

Related

Jquery capture tab + some key combination

How can I catch, for example, tab+t combination with jQuery? I've found a lot of examples with alt, shift and ctrl, since event object contains special flags in order to understand if, for example, alt was pressed. But there is not such thing for tab.
This should work. It's a bit convoluted and there is likely an easier way, but it works fine.
JSFiddle: https://jsfiddle.net/spybhhxc/
var tabdown = false;
var tdown = false;
$(document).keydown(function(e) {
if(e.which == 9) {
tabdown = true;
}
if(e.which === 84)
{
tdown = true;
}
if(tabdown && tdown)
{
//do your thing
}
});
$(document).keyup(function(e) {
if(e.which == 9) {
tabdown = false;
}
if(e.which === 84)
{
tdown = false;
}
});
This presents a problem though, as once you press tab, the document is unfocused as the tab key navigates to elements in a browser. You would be much better off using something like alt or ctrl which don't interact with the browser.
We can have a tab key pressed [tabPressed] variable which will be set to true on key down and unset the same on its key up event. We will using the tab key pressed[tabPressed] variable to check whether it is in pressed state during the other key press activities. The tab keycode is 9.
jsfiddle link http://jsfiddle.net/e3Lveyj2/
var tabPressed=false;
function handleKeyDown(e) {
var evt = (e==null ? event:e);
if(evt.keyCode == 9){
tabPressed=true;
}
if ((tabPressed) && (evt.keyCode == 84)) {
alert ("You pressed 'Tab+t'")
}
}
function handleKeyUp(e) {
var evt = (e==null ? event:e);
if(evt.keyCode == 9){
tabPressed=false;
}
}
document.onkeydown = handleKeyDown;
document.onkeyup = handleKeyUp;

How can I check that a key has been pressed?

Well I searched on Google but still didn't found the answer I was looking for.
I want to check if the user pressed a key, something like this -
if(document.onkeyup) {
// Some Stuff here
}
I know I can do this, this way -
document.onkeyup = getKey;
But the function getKey cannot return values.
So how can I check if the user pressed a key?
EDIT : I need pure Javascript for this thing..
You can do this in pure Javascript using the event object, without the need of external libraries such as jQuery.
To capture the keycode, just pass the event as parameter of getKey function:
function getKey(e)
{
window.alert("The key code is: " + e.keyCode);
}
document.onkeyup = getKey;
Frequently used keyCode list:
For a usefull list of keyCodes, you can check out this URL:
http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
Setting the keyCode to a global variable:
If you are interested in capturing the keyCode for later usage, you can do something like this:
var keycode = "";
(...)
function getKey(e)
{
keycode = e.keyCode;
}
document.onkeyup = getKey;
window.alert("The key code is: " + keycode);
Setting the keyCode to the event source object:
If you don't like global variables, like me, you could also do something like this:
function getKey(e)
{
keycode = e.keyCode;
var objectFromEvent = e.currentTarget ? e.currentTarget : event.srcElement;
objectFromEvent.customProperty = keycode;
}
document.customProperty = "";
document.onkeyup = getKey;
// now the value is in the "customProperty" of your object =)
window.alert("The key code is: " + document.customProperty);
One way you could do it is using variables
and then you could check that variable some were else...
for example
var keypressed = "";
document.onkeyup = function(e){
if (typeof event !== 'undefined') {
keypressed = event.keyCode;
}
else if (e) {
keypressed = e.which;
}
return false; // Prevents the default action
}
You really should not be doing this but if you really must:
var getKey = (function () {
var currentKey = null;
document.onkeyup = function (event) {
// determine the pressed key (across browsers)
// by inspecting appropriate properties of `event`
// and update currentKey; E.g:
currentkey = event.which ? event.which : window.event.keyCode;
}
return function () {
return currentkey;
}
})();
This will give you the last key user pressed.
If you need to get the currently pressed key (until released) then you need to attach keydown event to update currentKey variable and keyup event to set it to null.
You have to attach the event to the window global object and to set a function that listen to the event.
This sample show you how to track the keyup and keydown events.
window.addEventListener('keydown', onKeyDown, true);
window.addEventListener('keyup', onKeyUp, true);
function onKeyDown(evt) {
// key up event as been fired
console.log(evt.keyCode);
}
function onKeyUp(evt) {
// key up event as been fired
console.log(evt.keyCode);
}
See element.addEventListener on MDN for more details.
I would use jquery and do something like this:
// arrow keys click
$(document).keyup(function(e) {
// left arrow
if (e.keyCode == "37" ) {
// left stuff
// right arrow
} else if (e.keyCode == "39") {
// right stuff
// up arrow
} else if (e.keyCode == "38") {
// up stuff
// down arrow
} else if (e.keyCode == "40") {
// down stuff
}
});
etc, for the different key codes seen here http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
If you are attempting to run an event to test when a certain key is pressed, you can use this.
document.addEventListener('keydown', function(event) {
var key_code = event.keyCode;
if (key_code === 38) {
alert('test);
}
});

visualforce page javascript button click not working

I have a visualforce page (Salesforce) where I'm trying to capture the user pressing enter in a text field and firing a button click.
Here is my jquery code:
$(document).ready(function() {
$("#thisPage\\:theForm\\:siteNumber").keypress(function() {
if(window.event){
key = window.event.keyCode; //IE, chrome
}
else{
key = e.which; //firefox
}
if(key == 13) {
$("#thisPage\\:theForm\\:siteButton").click();
}
});
});
Its very odd, I've verified the key equals 13 and its entering the if statement. I've also tried moving the .click() action above the if key==13 condition and it fires fine. It just doesn't work inside the if key==13 condition I know its entering.
I've recreated what its basically doing in this simple fiddle, but of course it works fine: http://jsfiddle.net/2adPe/
Any help is appreciated!
UPDATE:
I've figured out that this will work
function noenter(e){
if(window.event){
key = window.event.keyCode; //IE, Chrome
}
else{
key = e.which; //firefox
}
if(key == 13) {
document.getElementById('thisPage:theForm:siteButton').click();
return false;
}
else{
return true;
}
}
with
onkeypress="return noenter(event)"
on the textbox. Is there a way to do this unobtrusively??
Try referencing your element IDs using the jQuery Attribute Ends With Selector.
Like this:
$("[id$='input1']").on("keypress",function(e) { // e is the current event
if(e){
key = e.keyCode; // IE, chrome
}
else{
key = e.which; // firefox
}
if(key == 13) {
e.preventDefault(); // prevent a form submit when pressing enter (on IE)
$("[id$='siteButton']").click(); // simulate a click of the siteButton
}
});
Also, you'll want to prevent the default action if the key == 13. Otherwise, the button click might be executed twice.
http://jsfiddle.net/2adPe/3/
Finally got it! I had to remove the e.preventdefault() from before the .click() and add return false at the end that stopped the default action from happening.
$('input[name$="siteNumber"]').keypress(function() {
if(window.event){
key = window.event.keyCode; //IE, chrome
}
else{
key = e.which; //firefox
}
if(key == 13) {
$('input[name$="siteButton"]').click();
return false;
}
});

Stuck alt / modifier key with Javascript

I have a library that creates an editor on the fly (http://epiceditor.com) and also sets up key shortcuts automatically. The shortcuts can be configured in the options so I can't use e.altKey, e.ctrlKey, etc just a heads up.
For some reason the modifier key isn't being set back to false sometimes on Mac/Ubuntu browsers.
On Windows it seems to happen every time. You can reproduce this by clicking render in JSBin then pressing alt+p. You should see "Yay" appear. Now, if on Windows press just p again. You'll see "Yay appear again. Mac and Ubuntu users have seen this same issue occasionally but it's hard to reproduce it.
Also note this only happens with the alt key it seems. Below I have 16 (shift) next to the 18 (alt). If you swap those out it'll work as expected.
The code for the stripped down test case is:
var modKey = false;
var modKeyCode = 18; //16
document.body.addEventListener('keydown', function (e) {
if (!modKey && modKeyCode == e.keyCode) {
modKey = true;
}
if (modKey && e.keyCode == 80) {
console.log('Yay!');
}
});
document.body.addEventListener('keyup', function (e) {
if (modKey && modKeyCode == e.keyCode) {
modKey = false;
}
});
Demo: http://jsbin.com/uhupah/3/edit#javascript,html
I do not have access to my Linux box at the moment, so i cannot test your code.
Thus here is more of a suggestion:
Linux (in my experience) is finicky when it it comes to keyCodes and order of key events. Perhaps combine the if(..) from keyup with that of keydown
if (!modKey && modKeyCode == e.keyCode) {
modKey = true;
} else if (modKey && modKeyCode == e.keyCode) {
modKey = false;
}
The above suggestion is made with assumption that you have no specific requirement to have both 'keydown' and 'keyup'.
I've come up with a fix, albeit a sort of crappy fix, but a fix nonetheless.
The fix I went with was to reset the modifier var when any key combo was successful. I.e. one the p in alt+p is pressed reset the modKey to false like this:
var modKey = false;
var modKeyCode = 18; //16
document.body.addEventListener('keydown', function (e) {
if (!modKey && modKeyCode == e.keyCode) {
modKey = true;
}
if (modKey && e.keyCode == 80) {
console.log('Yay!');
modKey = false; //THIS
}
});
document.body.addEventListener('keyup', function (e) {
if (modKey && modKeyCode == e.keyCode) {
modKey = false;
}
});
The problem with this tho is that you can't do back to back key commands. Most of the time this is alright because the user will do a key command like "save" or "preview" or something, type some more, then do another key command. But you wouldn't be able to, let's say: alt+p s to trigger alt+p then alt+s without having to let go of the alt key.

Simulate multiple keypresses in javascript

I would like to simulate the user pressing tab then enter when they press enter. I know this sounds bad, but I have an asp.net web application that will only allow me to have one form with runat="server" on it so when the user hits return the main form gets submitted. I have another textbox on the page though (that ideally should have it's own form but can't because it is asp), and when enter is hit from there obviously the main form is submitted. The simplest way I could think is to simulate tab then enter using javascript, but I have been unsuccessful in that. I am welcome to any other solutions to this problem. So far I have simulated pressing tab, but I don't know how to simulate more than one keypress though.
Here is the code I have so far, I imagine return 9; needs to be replaced with something else. JQuery will also do.
function suppressEnter (e) {
var keyPressed;
if (window.event) { keyPressed = window.event.keyCode } // IE
else if (e) { keyPressed = e.which }; // Netscape
if (keyPressed == 13) {
return 9;
}
else {
return true;
}
}
EDIT: return 9 + 13; works in chrome, but not IE
Something like this would work:
function keyPress(e) {
if (e.which == 13) {
$(document).trigger(jQuery.Event('keydown', {which: 9}));
// do something
alert('Enter')
}
if (e.which == 9) {
// do something
alert('Tab');
}
};
$(document).bind("keydown", keyPress);
I've coded it up in a fiddle - http://jsfiddle.net/FAe6U/
Also With regards to #nnnnnn comment:
It seems to me you should just code that directly rather than trying
to simulate keystrokes.
Try this:
var tabPress;
function keyPress(e) {
if (e.which == 13) {
if (tabPress == 1){
e.preventDefault();
alert('tab and enter');
}
else{e.preventDefault(); alert('enter')}
}
else if (e.which == 9) {
e.preventDefault();
tabPress = 1;
};
};
function keyRelease(){tabPress = 0;}
$(document).bind("keydown", keyPress);
$(document).bind("keyup", keyRelease);
I've coded it up in a fiddle - http://jsfiddle.net/f4Ybn/

Categories