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.
Related
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.
Rather vague title, I know, but I'm binding a custom key event to the document object to catch AltR combination keypresses, like this:
document.body.onkeydown = function(event){
event = event || window.event;
var keycode = event.charCode || event.keyCode;
if (keycode === 82) {
if (event.altKey) {
if (!canReload) {
canReload = true;
window.location.href += "#doGreaseRefresh";
} else {
canReload = false;
window.location.href = window.location.href.replace("#doGreaseRefresh", "");
}
return false;
}
}
}
The code runs as expected but also produces a rather annoying "beep" sound as well. How can I prevent this? return false didn't prove to be the answer, so I'm wondering if it's even possible.
Oh, and if you're wondering, this is in a Chrome userscript (Content script) to refresh Stack Overflow's home page every 10 seconds if I've pressed AltR, and to stop refreshing once I've pressed AltR again. :)
Not being able to stop the beep is apparently a bug in Chrome: http://code.google.com/p/chromium/issues/detail?id=105500. return false works in Firefox without a beep.
Cheers-
As ZachB points out, this appears to be a bug with Chrome.
To work around this annoyance:
Go into the Windows control panel.
Select Sounds or System Sounds
Assign (None) for the sound of the Default Beep.
(I like to do this anyway, since it's 50 times more annoying than it is useful).
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.
each browser has find on page functionality (ctrl+F). Is there a way to detect user searches in javascript so that I could attach additional actions.
Here is a solution which can account for alternative page find situations (ex. Command+F, '/' on Firefox). It checks for any of these keypresses and sets a timer when they occur. If the window is blurred soon after, then it is assumed that the Find dialog is showing.
Disadvantages: does not account for the "Find" dialog being launched via the menu. I don't see any way to be sure about this part, since (as far as I know, at least) browser UI is off-limits to Javascript running inside the DOM.
var keydown = null;
$(window).keydown(function(e) {
if ( ( e.keyCode == 70 && ( e.ctrlKey || e.metaKey ) ) ||
( e.keyCode == 191 ) ) {
keydown = new Date().getTime();
}
return true;
}).blur(function() {
if ( keydown !== null ) {
var delta = new Date().getTime() - keydown;
if ( delta >= 0 && delta < 1000 )
console.log('finding');
keydown = null;
}
});
jsFiddle, tested in Chrome, Safari and Firefox
You could do (to detect whenb a user press ctrl+f):
window.onkeydown = function(e){
if(e.keyCode == 70 && e.ctrlKey){
//user pressed ctrl+f
}
Fiddle here: http://jsfiddle.net/d8T72/
Of course you can try to hook into ctrl+f or cmd+f shortcut, but even if that works on "some" browsers, that way you only would know that an user pressed that shortcut and is most likely to search for something.
If the browser allows to overwrite that shortcut, you could further block the default behavior and implement your own search logic on the site. But that is considered most times as very bad practice. Overwritting native browser behavior is pretty pretty bad.
On the other hand, there is no "event" which gets triggered when a browser executed a search process. In short words, no, there actually is no way to detect or hook into a search process with javascript (if there is one, it's never gonna be cross browser compatible).
As initially suggested by #Nicola Peluchetti, here is a slightly improved version by feature sniffing:
window.onkeydown = function(e){
var ck = e.keyCode ? e.keyCode : e.which;
if(e.ctrlKey && ck == 70){
alert('Searching...');
}
}
Browser search test case ยป
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.