How to override Backspace key function in document as in Google - javascript

Friends I was making a calculator like project so It is a full webpage that displays my calculator. For inputs from keyboard all other keys worked. And I also want to use backspace key to do [del] command as in calculator. But it always goes to Backward visited site. Here's my code:
$(document).keypress(function(e){
var e=window.event || e
var keyunicode=e.charCode || e.keyCode
if(keyunicode>=40 && keyunicode<=57 && keyunicode!=44)
{
//call a function [worked]
}
else if(keyunicode==61)
{
// call another function worked.
}
else if(keyunicode==8)
{
e.preventDefault();
delete_last();
return false;
}
});
Please help. I tried in chrome..

You should use a keydown listener to catch backspace. keypress is meant for character keys. keydown is useful for functional keys.
$(document).keydown(function (e) {
if (e.which === 8) {
//your custom action here
return false;
}
});

Chrome does only support the keypress event for some keys and backspace is not among these. See http://code.google.com/p/chromium/issues/detail?id=2606 for details.
React to keydown and call preventDefault on the event to see an effect in Chrome, too.

Related

Firefox : override Alt + s key shortcut

I am working on an application where there are a lot key shortcuts for replication certain UI actions. One of such key shortcut combination is Alt + s
document.body.addEventListener('keyup',keyUpHandler,false);
function keyUpHandler(e)
{
e.stopPropagation();
var key = e.which || e.keyCode;
cellKeys(e,key);
}
function cellKeys(e,key){
if (e.altKey && key === 83) document.getElementById('saveCell').dispatchEvent(mouseclick); //alt + s
}
This key combination seems to work great for all other browsers except Mozilla firefox as this shortcut is used by the browser to open up history menu on top of the page.
I am looking for some workaround for this problem.
PS: I cannot use key down event listener and I have to use the same key combination. Also using e.preventDefault() was futile.
Be aware that some browsers will not allow you to capture certain shortcuts! A working example for the Alt+s shortcut in Mozilla Firefox:
window.onkeydown = function(e){
if(e.altKey && e.keyCode == 83){
e.preventDefault();
alert("Shotcut Pressed")
}
}

JavaScript Key Press at Document Level

So we are thinking about doing something like the code below to prevent a new window from opening.
var onkeydown = function() {
//alert(event.keyCode)
if ((event.keyCode == 78) && (event.ctrlKey)) {
alert ("No new window")
event.cancelBubble = true;
event.returnValue = false;
event.keyCode = false; return false;
}}
Our concern is that this block of code will get fired every time the user types a key, which makes sense. The site requires a lot of typing and entering data.
Is this a big concern? The block of code is small, but we were discussing that this could hinder performance?
Is this something that we should be worried about or is the code above simple enough that we should be ok?
We don't need to worry about opening a new window from the menu because it hidden.
That shouldn't be a problem as it will normally not enter the if-statement. As long as you don't have any other key event listeners, you should be fine.
You could use an eventhandler to listen for keypresses, and if the keys you pressed just so happen to be ctrl + n, you should use event.preventDefault to make sure it doesn't do what it's supposed to do.
window.addEventListener('keydown', function(e) {
var code = e.keyCode ? e.keyCode : e.which;
if(code == 78 && code == 17) { //ctrl + n
e.preventDefault();
alert("no new window");
//further actions
}
});
This listens if a key is down, then checks whether the keys you pressed are ctrl and N,
if so it prevents doing the default action and proceeds doing whatever you put inside the function.

How to override Ctrl + N in firefox to launch AJAX

Note: Juan Mendes answer is the selected answer because it had the most useful response to my situation. Though AxGryndr also had some useful information. Read both answers and they are both good for different situations. Thank you both for helping with this.
I already asked a similar question about this here which did solve the first part of my problem now I have another. I want the Ctrl + N to launch a script that contains an AJAX but once I run the .get function it cause the default to launch. Does anyone know a work around for this.
This fiddle has some code that shows my problem. Here is some of the code.
function checkkey(e)
{
if(e.ctrlKey && e.keyCode == 'N'.charCodeAt(0) && !e.shiftKey && !e.altKey)
{
try{e.preventDefault();}catch(ex){}
var m_objXMLHttpReqObj = new XMLHttpRequest();
m_objXMLHttpReqObj.open("GET", "", false);
m_objXMLHttpReqObj.send();
}
}
JSFIDDLE
Your code was not preventing the default behavior
function checkkey(e) {
if(e.ctrlKey && e.keyCode == 'N'.charCodeAt(0) && !e.shiftKey && !e.altKey) {
e.preventDefault();
// Now send your AJAX
It also seems that AJAX is interfering with the ability to stop the default behavior. You were trying to send a synchronous AJAX request (don't ever do that, it will halt the browser) and you weren't giving it a URL to go to (triggering an error). As soon as you change your settings to properly give it a URL and to make it asynchronous, then it does work in FF.
Here's the working code
function checkkey(e) {
if(e.ctrlKey && e.keyCode == 'N'.charCodeAt(0) && !e.shiftKey && !e.altKey){
e.preventDefault();
var m_objXMLHttpReqObj = new XMLHttpRequest();
m_objXMLHttpReqObj.open("GET",
// URL to go to
"/echo/html/",
// Asynchronous
true);
m_objXMLHttpReqObj.send("");
}
}
However, in Chrome (it may not be of use to you, but to others who read this answer), if you add a console.log at the top of your handler, you'll see that the handler never gets. Therefore, Chrome doesn't even let you see the CTRL+N combination and you can't do anything about it. Just like Windows applications don't get notified of CTRL+ALT+DEL
If the application has to work for multiple browsers, my suggestion is to use a different combination like ALT+SHIFT+N, you really don't want to take over the basic browser shortcuts.
I believe your issue is that you are checking for a keypress and performing your action too late after the keyup. If you change your code to bind to the keydown of Ctrl+N I think your would be able to get the desired result. Something like:
var pKey
$(function() {
$(window).keydown(function(e) {
if(e.which == 17) {
pKey = e.keyCode;
}
else {
if(pKey == 17 && e.keyCode == 78) {
e.preventDefault();
console.log(e);
}
}
});
});
I added the global variable to capture the Ctrl key down which is keycode 17. I then capture the keycode 78 on the second keydown which is the N. Prior e.preventDefault() was not enough to prevent the new window so I had to add the extra lines for e.stopPropagation(), e.stopImmediatePropagation() and the console.log(e) can be removed. As Juan M has mentioned the others are no longer needed so I have updated the code to not include them.
Note: Firefox made a change in key biding priority. It use to be System>Website>Firefox however it seems people were complaining about websites that hijacked short cuts so the priority has changed to be System>Firefox>Website which means even if your website binds Ctrl+N the priority of Firefox for a new windows takes over.

Handling Combo Keyboard Shortcuts

I want to simulate GMail/Twitter keyboard shortcuts of pressing a key, followed by another key to navigate somewhere in jQuery.
For example, G then H to go "Home" in GMail. Twitter also has G then H and other "combo" shortcuts.
Is there a jQuery plugin that simulates this behaviour?
I just released a library last week called mousetrap that has this functionality built in. Check out http://craig.is/killing/mice
You can do
Mousetrap.bind('g h', function() {
console.log('go home!');
});
Not sure about plugins, but you can achieve this other wise by keeping a key queue and processing that queue on each mouseup.
i.e. Something like:
var myKeyQueue = [];
$(document).keydown(function(e) {
var code e.charCode != 0 ? e.charCode : e.keyCode;
myKeyQueue.push(code);
});
$(document).keyup(function(e) {
processKeyQueue();
});
And you processKeyQueue function will be something like:
function processKeyQueue() {
// check if the Q contains any actionable key-combo, if so do it!
/*
if(myKeyQueue.length == 2) {
if(String.fromCharCode(myKeyQueue[0]) == 'G' && String.fromCharCode(myKeyQueue[0]) == 'H') {
// you code here ...
}
}
*/
if(myKeyQueue.length >= 2) {
myKeyQueue = []; // remove all keys in Q
}
}
Check out this Doing key combos with jQuery / JavaScript I think that it will answer your problem. Also this guy wrote his own VERY small plugin to handle CTRL+[Any Key] listener so that he could use shortcuts like CTRL+S to call a function that saves the active document, it might be able to be modified for your use
I think this: http://www.openjs.com/scripts/events/keyboard_shortcuts/
might help in some way for adding your own shotcuts

How can I disable Alt-Enter in IE?

As the default behavior of IE is to switch to the full screen mode on Alt-Enter command. I've to avoid this and have to attach a custom behavior.
Is it doable?
Not in JavaScript, no.
This is a behaviour of the application, which you don't really have control over (aside from browser extensions, and such).
You could try catching the key presses on your page, but it wouldn't prevent the user from easily circumventing it.
See http://www.webonweboff.com/tips/js/event_key_codes.aspx for a list of the character codes for keys. I'm pretty sure it's not reliable for catching combinations of key presses.
Besides, Alt+Enter in IE results in an expected behaviour and you should not try to override this via a webpage.
Since you can't beat 'em, join 'em. Meaning, since you can catch the event but can't stop it, how about you just run the same command in a timeout after the user presses alt+enter?
Example:
<script type="text/javascript">
document.onkeydown = handleHotKeys;
function handleHotKeys(e) {
var keynum = getKeyCode(e);
var e = e || window.event;
if (keynum==13 && e.altKey) { // handle enter+alt
setTimeout("toggleFullscreenMode",100);
}
}
function getKeyCode(e){
if (!e) { // IE
e=window.event;
return e.keyCode;
} else { // Netscape/Firefox/Opera
return e.which;
}
}
function toggleFullscreenMode() {
var obj = new ActiveXObject("Wscript.shell");
obj.SendKeys("{F11}");
}
</script>
DISCLAIMER: Tested in IE8. You will have to look at the browser and version to get this to work for the specific version of the browser you are targeting. This also assumes that the user will have javascript and activex objects enabled.

Categories