How do I get key values in HTML/Javascript - javascript

Okay, so i understand how to get the key value while using an input field... but I am taking about key values that are pressed while your browser isn't focused in any text box or text area.
I am trying to make a onscreen keypad that has buttons for 0, 1, 2, .. 9... however I want the user to be able to press the buttons with the keys on the keyboard.
I've seen this done in some websites, where if you press the S key on the homepage, it will take you to the signin screen. Facebook also does the L key, to like a photo.
So the question is: How do I get the key values in javascript, when the cursor isn't focused.

If you are using JQuery you just add the event handler to the document...
$(document).keypress(function(event) {
alert('Handler for .keypress() called. - ' + event.which);
});
(From http://forum.jquery.com/topic/how-to-catch-keypress-on-body)
Edit for zzzzBov's comment...
From the JQuery KeyPress documentation:
To determine which character was entered, examine the event object
that is passed to the handler function. While browsers use differing
properties to store this information, jQuery normalizes the .which
property so you can reliably use it to retrieve the character code.

you need to use window.onkeydown and then check for the keys you're interested in.
https://developer.mozilla.org/en-US/docs/Web/API/window.onkeydown

You should listen on key press event.
document.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
alert("Character typed: " + String.fromCharCode(charCode));
};
For more info Look here Link

You need to add an event listener to the window. Then in the event handler, you get the keyCode property from the passed-in event. KeyCodes are semi-arbitrary in that they don't directly map to what you might think, so you have to use a table (first result on google: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes) to identify the keycodes you care about.
window.addEventListener('keypress',function (evt) {
switch (evt.keyCode) {
case 48:
zeroKeyPressed(); break;
case 49:
oneKeyPressed(); break;
...
}
}, false);

You would use a key press event.
Here's an example for your usage:
window.addEventListener('keypress', function (event) {
var key_code, key;
event = event || window.event; // IE
key_code = event.charCode || event.keyCode || event.which || 0;
key = String.fromCharCode(key_code);
// prevent keys 0-9 from doing what they normally would do
if (key_code >= 48 && <= 57) {
event.preventDefault();
alert('The user pressed ' + key);
}
}, false);

Using plain js, you can use this in your layout.htmlcs, at the beginning:
#{
<script>
sessionStorage.setItem("ProductionHostURL", '#System.Configuration.ConfigurationManager.AppSettings["ProductionHostURL"]');
</script>
}
<!DOCTYPE html>
Then in your main js file of the layout.htmlcs, you can use this a method liked this:
var urlBaseProduction;
var urlBaseDevelopment;
$(document).ready(function () {
configureHostEnvironment()
....
}
In that method, configure the variables to use in production and development, like this:
function configureHostEnvironment(){
HOST = sessionStorage.getItem("ProductionHostURL")
if (HOST.length <= 0) {
alert("Host not configured correctly")
} else {
urlBaseProduction= host + '/api/';
urlBaseDevelopment= host + port + '/api/';
}
}
If you have a suggestion or improvement to this method, please comment.

Related

Get the key that was down while a double click was made in javascript

I would like to know what key was downed (held and pressed) while a double click event was fired on an element.
The event handler allows me to get alt, shift, meta and ctrl key. What if I want to detect whether 'x' was downed when a double click was made... Or any other letter or number for that matter.
If you want to detect ctrl, alt or shift keys, they are exposed on the event object that is passed to you.
$(document).on('dblclick', function(e){
/*
* here you could use e.altKey, e.ctrlKey and e.shiftKey - all of them
* are bools indicating if the key was pressed during the event.
*/
});
If you want to detect a different key, then omar-ali's answer seems to be the right thing to do.
You must store the keycode until the keyup event, and reference the current value at the time of the double-click event.
var heldKey;
$(document).on({
'keydown' : function(e) {
heldKey = e.which || e.keyCode;
},
'keyup': function(e) {
heldKey = undefined;
},
'dblclick': function(e){
console.log(String.fromCharCode(heldKey));
}
});
One possibility is to do this, 88 = the letter x.. but.. is there a better way.
$(document).on('keydown','body',function(e) {
//console.log(e.keyCode);
if(e.keyCode==88)
keyed = true;
});
$(document).on('keyup','body',function(e) {
if(e.keyCode==88)
keyed = false;
});
$(document).on('dblclick','body',function(e) {
if(keyed==true)
alert('yes');
keyed=false;
});

Submit form on press of specific key

Is there any way how to submit form when you press some predefined key on your keyboard (for example ; key)? I was thinking about something with onkeypress, but dont know how to set it just for one specific key.
Yes, and you were right with thinking onkeypress, just pass in the event, and check which key is pressed with event.which:
function keyPressed(event) {
if (event.which == 186) //keycode for semi-colon
console.log("Semi-colon pressed!");
}
}
Now just attach this function to a keypress handler.
Edit: Got the keycodes from here: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
You'll want to get the keycode and submit the form if it's the right keycode.
To get the keycode from an event, do:
$(document).on("keypress", function(event) {
var keyCode = event.keyCode;
var keyWhich = event.which;
if(keyCode = 'yourkey' || keyWhich = 'yourkey') {
$(form).submit();
}
});
For a full list of keycodes to replace 'yourkey' with, I'd recommend something like this cheat sheet. Just type your key in the input and use whatever value it provides as your function's logic
You can do this in jQuery:
$(document).ready( function() {
$(document).keydown(function(e){
if (e.keyCode == 186) { // ; key
$('#theform').submit();
}
});
});
See fiddle.

action by key press

I'm designing a web based accounting software. I would like to open the "new accounting document" whenever the user press N key for example. And open "settings" whenever he/she is pressing S key.
I saw some scripts based on JavaScript and jQuery. But they did not work exactly. Can anyone help me please ?
I have tried this script:
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) { //Enter keycode
//Do something
}
$(document).bind('keyup', function(e){
if(e.which==78) {
// "n"
}
if(e.which==83) {
// "s"
}
});
To prevent if an input is focused:
$("body").on("focus",":input", function(){ $(document).unbind('keyup'); });
$("body").on("blur",":input", function(){ $(document).bind('keyup', function(e){ etc.... });
You might want to put the bind function into its own function so you don't duplicate code. e.g:
function bindKeyup(){
$(document).bind('keyup', function(e){
if(e.which==78) {
// "n"
}
if(e.which==83) {
// "s"
}
});
}
$("body").on("focus",":input", function(){ $(document).unbind('keyup'); });
$("body").on("blur",":input", function(){ bindKeyup(); });
You can detech keypresses in jQuery using either .keypress() or .keyup() methods, here is a quick example :
$(document).keyup(function(event) { // the event variable contains the key pressed
if(event.which == 78) { // N keycode
//Do something
}
});
Here is a list of keycodes : http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
Update 1
.keyup and .keydown have different affects - as per comments from #ThomasClayson -: keyup is the best one to go for as keypress will repeat if the key is held down. it registers an event for each character inserted. It also doesn't register modifier keys such as shift (although not necessary here, it might be something to keep in mind)
Update 2
This is from the jQuery keyup doc site :
To determine which key was pressed, examine the event object that is
passed to the handler function. While browsers use differing
properties to store this information, jQuery normalizes the .which
property so you can reliably use it to retrieve the key code. This
code corresponds to a key on the keyboard, including codes for special
keys such as arrows.
Affectively meaning that which.event is all you need to determine which key has been used. Thanks #nnnnnn
You need to read up on the .keyCode() attribute of the event object. You can interrogate that to discover which key was pressed and act accordingly. I'd also suggest you add modifier keys to your shortcuts, such as Shift or Alt, so that when someone is innocently typing in an input, the panel doesn't pop up. In the example below I've used Shift
$(document).keyup(function(e) {
if (e.shiftKey) {
switch(e.keyCode ? e.keyCode : e.which) {
case 78: // N pressed
myNPressedHandler();
break;
case 83: // S pressed
mySPressedHandler();
break;
}
}
}
$(document).bind('keypress', function(e) {
var keycode= (e.keyCode ? e.keyCode : e.which);
if(keyCode==78) {
// "n"
}else if(keyCode==83) {
// "s"
}
});

Problem with event handler

function getFieldName(e) {
e = e || window.event;
var key = e.keyCode || e.which,
target = e.target || e.srcElement;
alert(target.name);
return (key != 13);
}
I have the above function called on body tag onkeypress = getFieldName(event);
I get the name of desired field but not able to check in IE as well as FF
if(target.name == 'check') {
// works fine in FF but in IE I'm not able
// to come inside this if-block, please suggest
}
thanks
I see you've tagged this post as jQuery... If you actually use jQuery to manage the event handler then you can use e.which to find the key that was pressed and e.target to find the DOM target. It also worries about the cross-browser stuff for you.
To attach a function as an event handler, you can follow this simple example:
$(document).keypress(getFieldName);
jQuery already normalizes some event properties internally, so you can just use event.target and event.which, you don't need to check for others, like this:
$(document).keypress(getFieldName);
function getFieldName(e) {
alert(e.target.name);
if(e.which == 13) {
alert("Key pressed was enter");
} else {
alert("Key pressed was not enter");
}
}
​
You can view a quick demo here

How to REALLY limit the available character for an input field using jQuery?

I just started adding JS-validation to a signup form and I want the username input field in a Twitter-style (using jQuery). That means that the input is limited to certain characters and other characters do not even appear.
So far, I've got this:
jQuery(document).ready(function() {
jQuery('input#user_login').keyup(function() {
jQuery(this).val( jQuery(this).val().replace(/[^a-z0-9\_]+/i, '') );
});
});
This solution works, but the problem is that the illegal character appears as long as the user hasn't released the key (please excuse my terrible English!) and the keyup event isn't triggered. The character flickers in the input field for a second and then disappears.
The ideal solution would be the way Twitter does it: The character doesn't even show up once.
How can I do that? I guess I'll have to intercept the input in some way.
If you want to limit the characters the user may type rather than the particular keys that will be handled, you have to use keypress, as that's the only event that reports character information rather than key codes. Here is a solution that limits characters to just A-Z letters in all mainstream browsers (without using jQuery):
<input type="text" id="alpha">
<script type="text/javascript">
function alphaFilterKeypress(evt) {
evt = evt || window.event;
var charCode = evt.keyCode || evt.which;
var charStr = String.fromCharCode(charCode);
return /[a-z]/i.test(charStr);
}
window.onload = function() {
var input = document.getElementById("alpha");
input.onkeypress = alphaFilterKeypress;
};
</script>
Try using keydown instead of keyup
jQuery('input#user_login').keydown(function() {
Aside: You selector is slower than it needs to be. ID is unique, and fastest, so
jQuery('#user_login').keydown(function() {
Should suffice
You might want to consider capturing the keycode iself, before assigning it to the val
if (event.keyCode == ...)
Also, are you considering the alt, ctls, and shift keys?
if (event.shiftKey) {
if (event.ctrlKey) {
if (event.altKey) {
Thanks #TimDown that solved the issue! I modified your code a little so it accepts backspace and arrows for editing (I post a reply to use code formatting).
Thank you very much.
function alphaFilterKeypress(evt) {
evt = evt || window.event;
// START CHANGE: Allow backspace and arrows
if(/^(8|37|39)$/i.test(evt.keyCode)) { return; }
// END CHANGE
var charCode = evt.keyCode || evt.which;
var charStr = String.fromCharCode(charCode);
// I also changed the regex a little to accept alphanumeric characters + '_'
return /[a-z0-9_]/i.test(charStr);
}
window.onload = function() {
var input = document.getElementById("user_login");
input.onkeypress = alphaFilterKeypress;
};
You can use the maxlength property in inputs and passwords: info (that's actually the way Twitter does it).

Categories

Resources