action by key press - javascript

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

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

Detect AltGr key using JavaScript

How can I clarify ALT+CTRL and ALTGR key press?
I found this code here as possible solution, but it's doesn't work:
if (event.ctrlKey && event.altKey) {
}
This code is true for alt+ctr and for altGr as well.
I have situation like this: for alt+ctrl+e (for example e, it's no matter) I want one thing and for altGr+e another, how can I do this?
If anyone have some idea, please tell me.
You can detect which key is pressed (from right key or left key) by value of location property in event object. If value of location property is 1 (e.location=1) then left key is pressed. if value is 2 then right key is pressed.
Here I have providing my code for RightAlter+RightCtrl+<any_valid_key>
Check this Example
var isRightAltKey=false;
var isRightCtrlKey=false;
var validKeys=['a','s','d','f','g']; //keep empty array if no need to check key
document.addEventListener("keydown", function(e) {
if(e.key=="Alt"){
// when right Alter pressed make isRightAltKey true
isRightAltKey= (e.location==2);
}
else if(e.key=="Control"){
// when right Control pressed make isRightCtrlKey true,
//if you need any ctrl key pressed then simply set isRightCtrlKey= true;
isRightCtrlKey= (e.location==2);
}
// checking both right key is pressed already or not?
var isRightKeys= isRightAltKey && isRightCtrlKey;
// validate other keys [optional]
var isValidKey=((typeof validKeys === "undefined") || validKeys.length==0 || validKeys.indexOf(e.key.toLowerCase())>=0);
if (isRightKeys && isValidKey){
document.getElementById("detect_key").innerHTML = "RightAlt + RightCtrl + "+e.key;
}
else
{
document.getElementById("detect_key").innerHTML="";
}
}, false);
document.addEventListener("keyup", function(e) {
if(e.key=="Alt"){
// when right Alter released make isRightAltKey false
isRightAltKey= false;
}
else if(e.key=="Control"){
// when right Control released make isRightCtrlKey false
isRightCtrlKey= false;
}
}, false);
<div id="detect_key"></div>
Why attached keyup event listner?
Here we have to detect key location when Ctrl and Alt key is pressed (on keydown event). and we have to store it in flag variable and make it true. when key is released (on keyup event) have to mark as false. Otherwise those flags always remain true. on Next key press it will always true
You can use the location to determined which alt is being pressed.
In order to support Alt+Ctrl we'll save the last location of the pressed Alt.
Location = 1 // Left
Location = 2 // Right
Then, once both Alt and Ctrl are pressed, do your thing. In this example, we'll just write the Alt side in the result div. You can add the "e" pressed condition as well:
if (e.ctrlKey && e.altKey && e.key == "e"){
Example
HTML
<div class="cont">
Click Alt + Ctrl<br /><br />
<div id="res"></div>
</div>
Javascript
var lastAltLocation;
document.addEventListener("keydown", function(e) {
if (e.key == "Alt"){
lastAltLocation = e.location;
}
if (e.ctrlKey && e.altKey){
if (lastAltLocation == 1){
document.getElementById("res").innerHTML = "Left";
}
if (lastAltLocation == 2){
document.getElementById("res").innerHTML = "Right";
}
}
}, false);
Sticking strictly to your question here are the codes for both the required cases:
document.addEventListener ("keydown", function (zEvent) {
if (zEvent.altKey && zEvent.code === "KeyE") {
if(zEvent.ctrlKey) {
//Do Ctrl+Alt+E Stuff Here.
} else {
//Do Alt+E Stuff Here.
}
});
Now breaking down the things going on here. keydown allows you to detect multiple keypresses.
First we check if the Alt and E keys are pressed. If yes, we then go on to check in the Ctrl key is also active and take the appropriate action as needed.

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.

How do I get key values in HTML/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.

Disable spaces in Input, AND allow back arrow?

I am trying to disable spaces in the Username text field, however my code disables using the back arrow too. Any way to allow the back arrow also?
$(function() {
var txt = $("input#UserName");
var func = function() {
txt.val(txt.val().replace(/\s/g, ''));
}
txt.keyup(func).blur(func);
});
fiddle: http://jsfiddle.net/EJFbt/
You may add keydown handler and prevent default action for space key (i.e. 32):
$("input#UserName").on({
keydown: function(e) {
if (e.which === 32)
return false;
},
change: function() {
this.value = this.value.replace(/\s/g, "");
}
});
DEMO: http://jsfiddle.net/EJFbt/1/
This seems to work for me:
<input type="text" onkeypress="return event.charCode != 32">
It doesn't "disable" the back arrow — your code keeps replacing all the text outright, whenever you press a key, and every time that happens the caret position is lost.
Simply don't do that.
Use a better mechanism for banning spaces, such as returning false from an onkeydown handler when the key pressed is space:
$(function() {
$("input#Username").on("keydown", function (e) {
return e.which !== 32;
});​​​​​
});
This way, your textbox is prohibited from receiving the spaces in the first place and you don't need to replace any text. The caret will thus remain unaffected.
Update
#VisioN's adapted code will also add this space-banning support to copy-paste operations, whilst still avoiding text-replacement-on-keyup handlers that affect your textbox value whilst your caret is still active within it.
So here's the final code:
$(function() {
// "Ban" spaces in username field
$("input#Username").on({
// When a new character was typed in
keydown: function(e) {
// 32 - ASCII for Space;
// `return false` cancels the keypress
if (e.which === 32)
return false;
},
// When spaces managed to "sneak in" via copy/paste
change: function() {
// Regex-remove all spaces in the final value
this.value = this.value.replace(/\s/g, "");
}
// Notice: value replacement only in events
// that already involve the textbox losing
// losing focus, else caret position gets
// mangled.
});​​​​​
});
Try checking for the proper key code in your function:
$(function(){
var txt = $("input#UserName");
var func = function(e) {
if(e.keyCode === 32){
txt.val(txt.val().replace(/\s/g, ''));
}
}
txt.keyup(func).blur(func);
});
That way only the keyCode of 32 (a space) calls the replace function. This will allow the other keypress events to get through. Depending on comparability in IE, you may need to check whether e exists, use e.which, or perhaps use the global window.event object. There are many question on here that cover such topics though.
If you're unsure about a certain keyCode try this helpful site.
One liner:
onkeypress="return event.which != 32"

Categories

Resources