Combination of Keypresses using JS / jQuery ( Escape & Shift +Escape ) - javascript

Is there a way in js/jQuery how to have these two combinations of keypresses?
ESCape key
and
SHIFT + ESCape key
when I implemented it using:
document.onkeydown = function(e){if (e == null) {keycode = event.keyCode;}
else {keycode = e.which;}
if(keycode == 27){closeAll();}}
//upon pressing shift + esc
$(document).bind('keypress',function(event)
{
if(event.which === 27 && event.shiftKey)
{
closetogether();
}
});
The escape button works perfectly but the one with the shift + esc is getting confused I think because it's doing nothing. Don't worry the function works as when I change the combining key 27 to 90 (z) for example it works just fine.
Can someone opt me for a better way ?

Why don't you bind the keydown event using jQuery? That way you would already have a normalized event variable. You can also check the status of the shift key in the same handler.
These events send different keycodes back. Use keyup/keydown for capturing certain keys by scancodes and use keypress to capture actual text input by characters.
$(document).bind('keydown', function(event) {
if(event.which === 27){
if(event.shiftKey){
closetogether();
} else {
closeAll();
}
}
});

Related

Detect backspace and special characters using javascript

I want to detect these two behaviours on an input field:
1)Backspace key
2)"#" and "#" key
By using jQuery's keypress function, I am able to detect the special characters but not backspace.
LINK -> How to know if .keyup() is a character key (jQuery)
By using jQuery's keyup/keydown, I am able to detect backspace, but not special characters.
LINK -> jQuery: keyPress Backspace won't fire?
How can I detect both the behaviours ?
NOTE: Keypress can detect backspace in firefox only. Chrome doesn't detect this.
You can use following snippet:
var keys = {};
$('input').keydown(function (e) {
keys[e.which] = true;
});
$('input').keyup(function (e) {
getKeys();
delete keys[e.which];
});
function getKeys() {
if(keys[8]) {
alert('bakspace pressed');
}else if(keys[17] && keys[18] && keys[48]) {
alert('# pressed');
}else if(keys[17] && keys[18] && keys[51]) {
alert('# pressed');
}
}
DEMO
original post: https://stackoverflow.com/a/4954480/1414562

jquery mobile - keyup keydown on mobile devices

I have a need for an input (type='text') to go send results to the my server to check availability of something typed by the user.
I use the delegate to add the event handlers to the elements:
$(document).delegate('#signup', 'pageshow', function() {
var keydown = function(e) {
e = e || window.event;
var char = e.which || e.keyCode;
if (char == 8) {
$(".pagemessage").text("Pressed: '<BACKSPACE>'");
appcheckDomainOnKeyDown();
}
return true;
};
var keyup = function(e) {
e = e || window.event;
var char = e.which || e.keyCode;
if (char == 8) {
appcheckDomainOnKeyUp();
}
return true;
};
var keypress = function(e) {
e = e || window.event;
var char = e.which || e.keyCode;
var str = String.fromCharCode(char);
$(".pagemessage").text("Pressed: '" + str +"'");
if (/[a-zA-Z0-9-\._]/.test(str) || char == 8 || char == 9) {
appcheckDomainOnKeyDown();
appcheckDomainOnKeyUp();
return true;
}
return false;
};
The key handers work perfectly on my desktop but not on a mobile device. Hopefully you can see that I'm trying to allow certain characters into the box (and a backspace to delete the characters.
From the fact I cannot see the pagemessage element update, 'keypress' does not seem to be trapped. I tried handling this in the keyup/keydown, but I'm not sure how to apply the shiftKey bits to get an actual character pressed - for example pressing + 5 would give '%' however in the keydown it returns shiftKey and 5.
I read the documentation and the closest I could find to 'keypress' was a 'tap' event, but that didn't work either.
I have tried trapping the 'keypress' event as suggested in one post here, and on a desktop this does not trap the backspace, and does nothing at all on a mobile device.
I then tried this as suggested in another post:
var inputEV = 'oninput' in window ? 'input' : 'keyup';
$("#new_domain").off(inputEV);
$("#new_domain").on(inputEV, function (e) {
keydown(e);
keyup(e);
});
and it does not work in either desktop browser or mobile device.
I then tried changing the input type to 'search', and I get a pretty enhancement, that a keypress does add a clear button... but does nothing on the mobile device regarding my own functionality.
I think I have run out of things to try, the only thing left is to add a button to go check - and no one wants that :)
Anyone know how I can do what I need?
In case it's relevant, I'm using chrome on my desktop and android device (HTC one, and Nexus 5)
Keyup should work. It works in this example: http://jsbin.com/aNEBIKA/2/. That tested find on my Galaxy S3. Each keypress updates the footer h3 element with the text entered.
Could it be that you are binding your listeners at the wrong time? The documentation does suggest binding like this:
$(document).bind('pageinit')
http://demos.jquerymobile.com/1.2.0/docs/api/events.html

Change key by other in keypress event or keydown event

When my user press "." I need that browser show ",".
I intent use this Extjs code buy don't work :(
Ext.EventManager.on(document, 'keypress', function(evt, t, o) {
if (evt.keyCode == 46) { // .
evt.keyCode = 44; // ,
}
});
Any idea?
You are changing the value of the event, and that's not going to change the value of the resultant string.
You should replace the . for the ,on the string ater you catch the event:
Ext.EventManager.on(document, 'keypress', function(evt, t, o) {
if (evt.keyCode == 46) { // .
resultantString.replace('.', ',');
}
});
Obviously, this won't work, because you are merely changing the keyCode. That won't somehow reflect on the screen. You will have to locate the element that caused the event and set its text to (whatever was before) + (remove the .) + (,)
Of course, this is the long way out. I hope someone has a shorter way.

Remove Any Spaces While Typing into a Textbox on a Web Page Part II

This involves HTML + JS and/or JQuery:
I would have commented on the previous post, but I don't have comment reputation or cannot comment for some reason.
Josh Stodola's great code from Part I is as follows:
$(function() {
var txt = $("#myTextbox");
var func = function() {
txt.val(txt.val().replace(/\s/g, ''));
}
txt.keyup(func).blur(func);
});
This works great except .replace puts the cursor at the end of the string on every keyup (at least in IE8 and Chrome).
As a result, it renders the left & right cursor keys useless, which is needed inside the input box.
Is there any way to enhance the above code so that the cursor keys do not activate it, but so that the text still gets updated on the fly?
The best solution is to avoid using key events to capture text input. They're not the best tool for the job. Instead, you should use the HTML5 oninput event (supported in the latest and recent versions of every current major browser) and fall back to onpropertychange for older versions of Internet Explorer:
var alreadyHandled;
txt.bind("input propertychange", function (evt) {
// return if the value hasn't changed or we've already handled oninput
if (evt.type == "propertychange" && (window.event.propertyName != "value"
|| alreadyHandled)) {
alreadyHandled = false;
return;
}
alreadyHandled = true;
// Your code here
});
These events don't fire for keys that don't result in text entry — don't you just hate it when you shift-tab back to a form element and the resulting keyup event causes the page's script to move focus forward again?
Additional benefits over key events:
They fire immediately when the key is pressed and not when the key is lifted, as in keyup. This means you don't get a visual delay before any adjustments to the text are made.
They capture other forms of text input like dragging & droppping, spell checker corrections and cut/pasting.
Further reading at Effectively detecting user input in JavaScript.
Update the function:
var func = function(e) {
if(e.keyCode !== 37 && e.keyCode !== 38 && e.keyCode !== 39 && e.keyCode !== 40){
txt.val(txt.val().replace(/\s/g, ''));
}
}
try:
$(function() {
var txt = $("#myTextbox");
var func = function(e) {
if(e.keyCode != "37" && e.keyCode != "38" && e.keyCode != "39" && e.keyCode != "40"){
txt.val(txt.val().replace(/\s/g, ''));
}
}
txt.keyup(func).blur(func);
});
$(function() {
var txt = $("#myTextbox");
var func = function() {
txt.val(txt.val().replace(/\s/g, ''));
}
txt.keyup(function(evt){
if(evt.keyCode < 37 || evt.keyCode > 40) {
func;
}
}).blur(func);
});
Something like that should do it. It will run the function if the keycode isn't 37,38,39 or 40 (the four arrow key keycodes). Note that it won't actually stop the cursor position moving to the end when any other key is pressed. For that, you'd need to keep track of the current cursor position. Take a look at this link for jCaret plugin, which can do this

JavaScript can't capture "SHIFT+TAB" combination

For whatever reason I can't capture "SHIFT+TAB" combination.
I am using the latest jQuery.
Same result if I use other ajax/javascript, etc.
Here is a simple example that should work as I currently understand it...
event.which or event.KeyCode are always "undefined" only shiftKey exists in a scenario involving a "SHIFT+TAB" or backward keyboard traversal, traditionally inherent in windows based apps/web or otherwise...
function ShiftTab()
{
debugger;
if(event.KeyCode == 9 && event.shiftKey) // neither this line nor the following work
// if (event.which == 9 && event.shiftKey) // shift + tab, traverse backwards, using keyboard
{
return true;
}
else
{
return false;
}
}
this seems to be yet another item related to tab order that no longer works as it traditionally worked in Microsoft.Net WinForm/WebForm based apps.
If you are using jQuery, this should be how the code is working. Make sure keyCode is lower case. Also, jQuery normalizes keyCode into which:
$(document).keyup(function (e) {
if (e.which === 9 && e.shiftKey) {
ShiftTab();
}
});
If you're into terse JavaScript:
$(document).keyup(function (e) {
e.which === 9 && e.shiftKey && ShiftTab();
});
jQuery 1.7+ on syntax:
$(document).on('keyup', function (e) {
e.which === 9 && e.shiftKey && ShiftTab();
});
I created a function which I wired up to my button's onkeydown event. I used onkeydown, because onkeypress would not capture my tab key press
function ShiftTab(evt) {
var e = event || evt; // for trans-browser compatibility
var charCode = e.which || e.keyCode; // for trans-browser compatibility
if (charCode === 9) {
if (e.shiftKey) {
$('#controlName').focus();
return false;
} else {
return true;
}
}
I took this approach to deal with two specific problems:
onkeypress would not capture tab key press
When click shift-tab, shift key press would trigger function, so I had nest the shiftkey modifier check
use same code inside keypress event.
the tab changes the element between keypress and keyup.
here we get event.key = tab and event.shiftKey = true.

Categories