I write this Javascript code but it doesn't disable 2 windows keys (I mean logo key and menu key), though:
document.onkeydown = function(e) {
document.title = e.keyCode;
if (e.keyCode == 91 || e.keyCode == 93) {
window.event.keyCode = 0;
window.event.returnValue = false;
return false;
}
};
the 2 window.xxx statements are actually not necessary but I add them in to buy an insurance (Just doubt that e doesn't totally equal to window.event).
So I'd like to ask this question: " Is there a feasible way, directly or indirectly, to do this job in Javascript? "
Your code looks right, try to find out real keycodes with this simple script:
document.onkeydown = checkKeycode
function checkKeycode(e) {
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
alert("keycode: " + keycode);
}
And to disabel certain keys you modify function (example for 'Enter'):
document.onkeydown = checkKeycode
function checkKeycode(e) {
var event = e || window.event;
var keycode = event.which || event.keyCode;
if (keycode == 13) {
// return key was pressed
}
}
JavaScript cannot stop the effect of the Windows logo key, which (when released) is supposed to bring up the Window's start menu. In combination with other keys, it has other system wide effects (like with M = minimise all windows). This is something that happens outside of the browser context, and thus cannot and should not be blocked by the code running in your browser.
The Windows menu key can be somewhat disabled, as described in this answer:
$(function(){
var lastKey=0;
$(window).on("keydown", document, function(event){
lastKey = event.keyCode;
});
$(window).on("contextmenu", document, function(event){
if (lastKey === 93){
lastKey=0;
event.preventDefault();
event.stopPropagation();
return false;
}
});
});
Related
I want to use shortcut to handle a task in Javascript (not JQuery or any Javascript libraries). For example, I want to use Ctrl+Q to write an alert. My issue is only to use Ctrl+Q, combination of other keys such as Ctrl+Q+other key will not handle the alert. How can I do?
document.addEventListener('keydown', function(event){
if(event.ctrlKey && event.keyCode == 81) console.log('alert');
});
I only want Ctrl+Q work, not for Ctrl+Shift+Q, Ctrl+Alt+Q, Ctrl+Q+(some key else)
Just ensure none of the other three modifiers are pressed:
document.addEventListener('keydown', function(event) {
if (event.ctrlKey && event.keyCode == 81 && !(event.shiftKey || event.altKey || event.metaKey)) console.log("alert");
});
The code below should solve your problem(Updated Code):
document.addEventListener("keydown", function (event) {
var map = [];
onkeyup = function(e){
map.push(e.key);
console.log(map);
if(map.length == 2){
console.log("CTRL + Q was pressed",map.indexOf("q") > -1 && map.indexOf("Control") > -1)
}
onkeydown = function(e){
// console.log(map);
}
}
});
If any other button is pressed along with ctrl (For instance: ctrl+shift+Q or ctrl+alt+q), it returns false!! Let me know if that solves your problem. Cheers!!
You'll need to keep track of what keys are pressed with keydown and which keys are released with keyup, then, when a new key is pressed, you would check for only Ctrl and Q currently being down.
Something like this should work:
var keysPressed = [];
function onPressOrRelease(event) {
if (event.type === "keydown") {
if (!keysPressed.includes(event.keyCode))
keysPressed.push(event.keyCode)
} else if (event.type === "keyup")
keysPressed.splice(keysPressed.indexOf(event.keyCode), 1);
let ctrlQPressed = keysPressed.includes(81) && keysPressed.includes(17) && !keysPressed.some(a => a !== 81 && a !== 17)
if (ctrlQPressed)
console.log("pressed");
}
document.addEventListener("keydown", onPressOrRelease);
document.addEventListener("keyup", onPressOrRelease);
You'll want to make sure keys don't get added multiple times and may want to clear the array on focus loss (since using control it may lose focus when releasing)
I am trying to add a keylistener to my input field but I can't make it work. My input type is text with id= "code". Here is what I tried:
document.querySelector('code').addEventListener('keypress', function (e) {
var key = e.which || e.keyCode;
window.alert(key);
});
and
document.getElementById('code').addEventListener("keydown", dealWithKeyboard, false);
function dealWithKeyboard(e) {
if (window.event) { // IE
keynum = e.keyCode;
} else if (e.which) { // Netscape/Firefox/Opera
keynum = e.which;
}
window.alert(keynum);
}
and
document.getElementById('code').onkeyup = function(e) {
if (window.event) { // IE
keynum = e.keyCode;
} else if (e.which) { // Netscape/Firefox/Opera
keynum = e.which;
}
window.alert(keynum);
}
But none seems to work
You aren't using the proper selector with document.querySelector(). An id value must be preceded by # as in document.querySelector('#code').
document.querySelector('#code').addEventListener('keypress', function (e) {
var key = e.which || e.keyCode;
console.log(key);
});
Working snippet:
document.querySelector('#code').addEventListener('keypress', function (e) {
var key = e.which || e.keyCode;
log(key);
});
// show output
function log(x) {
var div = document.createElement("div");
div.innerHTML = x;
document.body.appendChild(div);
}
Type some characters in the Input field here:
<input id="code">
Implemented properly, your document.getElementById('code') example should work.
If this still doesn't work, then check for two more things:
Make sure that you are executing this script AFTER the relevant parts of the DOM have been loaded. There are several ways to assure this, but the simplest is to just located the <script> tag after the HTML that it refers to.
Make sure that there are no script errors that are preventing your code from executing. You can check the debug console to check for errors.
I have a problem with javascript keys, Chrome (only testing on chrome right now) does not recognise up and down arrows on text input, as it has this default behaviour in which it changes the caret position.
My code is as follows:
if (!e) e = window.event;
var keyCode = e.keyCode || e.which;
if (keyCode == '13'){ //enter key
//some code that works
return false;
}else if(keyCode=='38'){ //up key
//some other code that doesn't work
return false;
}else if(keyCode=='40'){ //down key
//some other code that doesn't work
return false;
}
If anyone has a solution I will greatly appreciate it.
Thank you!
Hard to see where the code is from (an keypress listener I guess).
As you can see below and this fiddle (and as Teemu also pointed out), keypress won't get called on arrow keys.
On another note, use event.preventDefault() to prevent the default behaviour of the browser, in your case the placing of the caret, also your listener functions can except an event object as a parameter.
var listener = function (e) {
e = e || window.event;
alert(e.type);
var keyCode = e.keyCode || e.which;
if(keyCode=='38' || keyCode=='40'){ //arrow key
alert("arrow!");
e.preventDefault();
return false;
}
}
var elem = document.getElementById('input');
elem.addEventListener('keydown', listener, false);
<script>
function MoveNext(e, obj) {
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
if (code == 13) {
document.getElementById(obj).focus();
return false;
}
</script>
the above code is working in IE but not in mozilla why
change
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
to
code = (e.keyCode)? e.keyCode: e.charCode;
and make sure your are passing your event to moveNext when you are calling it because firefox recognise event only if you sent it explicitly from the function.
also if your object that your are doing keydown is a div add to it a tabindex of 0 so it can retrieve focus .
<div id="mydiv" tabindex="0"></div>
Exactly what the best code is for the return key depends upon which keyboard event you are listening to (keydown, keyup, keypress). For keypress, you can do it like this:
function MoveNext(e, obj) {
e = e || window.event;
var code = e.which || e.keyCode;
if (code == 13) {
document.getElementById(obj).focus();
}
}
Note: I've remove your local variable e so it doesn't get confused with the argument e and I've defined code as a local variable which you had as an implicit global variable (never a good thing).
More on cross browser key handling described here: keycode and charcode.
Possible Duplicate:
Which keycode for escape key with jQuery
How to detect escape key press in IE, Firefox and Chrome?
Below code works in IE and alerts 27, but in Firefox it alerts 0
$('body').keypress(function(e){
alert(e.which);
if(e.which == 27){
// Close my modal window
}
});
Note: keyCode is becoming deprecated, use key instead.
function keyPress (e) {
if(e.key === "Escape") {
// write your logic here.
}
}
Code Snippet:
var msg = document.getElementById('state-msg');
document.body.addEventListener('keypress', function(e) {
if (e.key == "Escape") {
msg.textContent += 'Escape pressed:'
}
});
Press ESC key <span id="state-msg"></span>
keyCode is becoming deprecated
It seems keydown and keyup work, even though keypress may not
$(document).keyup(function(e) {
if (e.key === "Escape") { // escape key maps to keycode `27`
// <DO YOUR WORK HERE>
}
});
Which keycode for escape key with jQuery
The keydown event will work fine for Escape and has the benefit of allowing you to use keyCode in all browsers. Also, you need to attach the listener to document rather than the body.
Update May 2016
keyCode is now in the process of being deprecated and most modern browsers offer the key property now, although you'll still need a fallback for decent browser support for now (at time of writing the current releases of Chrome and Safari don't support it).
Update September 2018
evt.key is now supported by all modern browsers.
document.onkeydown = function(evt) {
evt = evt || window.event;
var isEscape = false;
if ("key" in evt) {
isEscape = (evt.key === "Escape" || evt.key === "Esc");
} else {
isEscape = (evt.keyCode === 27);
}
if (isEscape) {
alert("Escape");
}
};
Click me then press the Escape key
Using JavaScript you can do check working jsfiddle
document.onkeydown = function(evt) {
evt = evt || window.event;
if (evt.keyCode == 27) {
alert('Esc key pressed.');
}
};
Using jQuery you can do check working jsfiddle
jQuery(document).on('keyup',function(evt) {
if (evt.keyCode == 27) {
alert('Esc key pressed.');
}
});
check for keyCode && which & keyup || keydown
$(document).keydown(function(e){
var code = e.keyCode || e.which;
alert(code);
});
Pure JS
you can attach a listener to keyUp event for the document.
Also, if you want to make sure, any other key is not pressed along with Esc key, you can use values of ctrlKey, altKey, and shifkey.
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape') {
//if esc key was not pressed in combination with ctrl or alt or shift
const isNotCombinedKey = !(event.ctrlKey || event.altKey || event.shiftKey);
if (isNotCombinedKey) {
console.log('Escape key was pressed with out any group keys')
}
}
});
pure JS (no JQuery)
document.addEventListener('keydown', function(e) {
if(e.keyCode == 27){
//add your code here
}
});
Below is the code that not only disables the ESC key but also checks the condition where it is pressed and depending on the situation, it will do the action or not.
In this example,
e.preventDefault();
will disable the ESC key-press action.
You may do anything like to hide a div with this:
document.getElementById('myDivId').style.display = 'none';
Where the ESC key pressed is also taken into consideration:
(e.target.nodeName=='BODY')
You may remove this if condition part if you like to apply to this to all. Or you may target INPUT here to only apply this action when the cursor is in input box.
window.addEventListener('keydown', function(e){
if((e.key=='Escape'||e.key=='Esc'||e.keyCode==27) && (e.target.nodeName=='BODY')){
e.preventDefault();
return false;
}
}, true);
Best way is to make function for this
FUNCTION:
$.fn.escape = function (callback) {
return this.each(function () {
$(document).on("keydown", this, function (e) {
var keycode = ((typeof e.keyCode !='undefined' && e.keyCode) ? e.keyCode : e.which);
if (keycode === 27) {
callback.call(this, e);
};
});
});
};
EXAMPLE:
$("#my-div").escape(function () {
alert('Escape!');
})
On Firefox 78 use this ("keypress" doesn't work for Escape key):
function keyPress (e)(){
if (e.key == "Escape"){
//do something here
}
document.addEventListener("keyup", keyPress);
i think the simplest way is vanilla javascript:
document.onkeyup = function(event) {
if (event.keyCode === 27){
//do something here
}
}
Updated: Changed key => keyCode