Capturing ctrl+z key combination in javascript - javascript

I am trying to capture ctrl+z key combination in javascript with this code:
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<script type='text/javascript'>
function KeyPress(e) {
var evtobj = window.event? event : e
//test1 if (evtobj.ctrlKey) alert("Ctrl");
//test2 if (evtobj.keyCode == 122) alert("z");
//test 1 & 2
if (evtobj.keyCode == 122 && evtobj.ctrlKey) alert("Ctrl+z");
}
document.onkeypress = KeyPress;
</script>
</body>
</html>
Commented line "test1" generates the alert if I hold down the ctrl key and press any other key.
Commented line "test2" generates the alert if I press the z key.
Put them together as per the line after "test 1 & 2", and holding down the ctrl key then pressing the z key does not generate the alert as expected.
What is wrong with the code?

Use onkeydown (or onkeyup), not onkeypress
Use keyCode 90, not 122
function KeyPress(e) {
var evtobj = window.event? event : e
if (evtobj.keyCode == 90 && evtobj.ctrlKey) alert("Ctrl+z");
}
document.onkeydown = KeyPress;
Online demo: http://jsfiddle.net/29sVC/
To clarify, keycodes are not the same as character codes.
Character codes are for text (they differ depending on the encoding, but in a lot of cases 0-127 remain ASCII codes). Key codes map to keys on a keyboard. For example, in unicode character 0x22909 means 好. There aren't many keyboards (if any) who actually have a key for this.
The OS takes care of transforming keystrokes to character codes using the input methods that the user configured. The results are sent to the keypress event. (Whereas keydown and keyup respond to the user pressing buttons, not typing text.)

For future folks who stumble upon this question, here’s a better method to get the job done:
document.addEventListener('keydown', function(event) {
if (event.ctrlKey && event.key === 'z') {
alert('Undo!');
}
});
Using event.key greatly simplifies the code, removing hardcoded constants. It has support for IE 9+.
Additionally, using document.addEventListener means you won’t clobber other listeners to the same event.
Finally, there is no reason to use window.event. It’s actively discouraged and can result in fragile code.

Ctrl+t is also possible...just use the keycode as 84 like
if (evtobj.ctrlKey && evtobj.keyCode == 84)
alert("Ctrl+t");

$(document).keydown(function(e){
if( e.which === 89 && e.ctrlKey ){
alert('control + y');
}
else if( e.which === 90 && e.ctrlKey ){
alert('control + z');
}
});
Demo

document.onkeydown = function (e) {
var special = e.ctrlKey || e.shiftKey;
var key = e.charCode || e.keyCode;
console.log(key.length);
if (special && key == 38 || special && key == 40 ) {
// enter key do nothing
e.preventDefault();
}
}
here is a way to block two keys, either shift+ or Ctrl+ key combinations.
&& helps with the key combinations, without the combinations, it blocks all ctrl or shift keys.

90 is the Z key and this will do the necessary capture...
function KeyPress(e){
// Ensure event is not null
e = e || window.event;
if ((e.which == 90 || e.keyCode == 90) && e.ctrlKey) {
// Ctrl + Z
// Do Something
}
}
Depending on your requirements you may wish to add a e.preventDefault(); within your if statement to exclusively perform your custom functionality.

The KeyboardEvent.keyCode is deprecated (link) think about using KeyboardEvent.key instead (link).
So, the solution would be something like this.
if (e.key === "z" && e.ctrlKey) {
alert('ctrl+z');
}

You can actually see it all in the KeyboardEvent when you use keydown event

Use this code for CTRL+Z. keycode for Z in keydown is 90 and the CTRL+Z is ctrlKey. check this keycode in your console area
$(document).on("keydown", function(e) {
console.log(e.keyCode, e.ctrlKey);
/*ctrl+z*/
if (e.keyCode === 90 && e.ctrlKey) { // this is confirmed with MacBook pro Monterey on 1, Aug 2022
{
//your code here
}
});

Related

Pure JavaScript to detect only Ctrl+Q shortcuts

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)

Determine if key pressed is writing something - Javascript

I want to run an action only if the key pressed is writing something, so it ignores arrow keys, shift key or enter key etc.
I am using the following script, but I would like to find an alternative to Improve it.
$('body').on('keyup', 'input', function(e) {
if (e.keyCode >= 48 && e.keyCode <= 57 || e.keyCode >= 65 && e.keyCode <= 90 || e.keyCode >= 97 && e.keyCode <= 122) {
// do something
}
});
From the comments:
the problem is my script include only the Number, Alphabet upper case and Alphabet lower case.I want to run action only if input content change
In order to trigger an event when text changes in the input, you need to define a global variable holding the previous data of the input.
Then when a keyup event is fired, you can check whether the input_data==new_input_data, then do whatever you want.
var input_data, new_input_data;
input_data = $("#myinput").val();
new_input_data="";
$('body').on('keyup', 'input', function(e) {
new_input_data = $("#myinput").val();
if(input_data!=new_input_data){
alert("text changed");
input_data = new_input_data;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="myinput" />

Detecting left and right control keys in Javascript

I have a text input, where I need to bind an event on doing a CTRL-V. I have set a global variable named ctrl which is set to 1 whenever a keydown is fired with a which value of 17. Similarly it is made 0 when a keyup is fired with which value of 17
Problem is, there are two CTRL keys. So if I do something like: first pressing the left CTRL key, and while pressing it down, press the right CTRL key also (so that both CTRL keys are pressed now), and then I release only one of them, the keyup is fired and the variable ctrl is set to 0, even though the other CTRL key is still being pressed.
How do I fire the events such that the variable is set to 0 only when both CTRL keys are up (I don't need to exactly differentiate between them).
Update : this is now possible in modern browsers
The easiest way to detect left and right control keys in Javascript
$(document).ready(function(){
$("html").keydown(function(e) {
if (e.ctrlKey) {
if (event.location == 1) console.log('left ctrl');
if (event.location == 2) console.log('right ctrl');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Note: You have to click the inside white space when you run code snippet to activate keyboard keys. This is tested in Chrome and Safari.
There are two properties for this of keydown event.
You can differentiate left and right Ctrl by using
if ( e.location == 1 || e.keyLocation == 1 ) {
var keyPosition = 'left';
} else if ( e.location == 2 || e.keyLocation == 2 ) {
var keyPosition = 'right';
}
I don't think there is a way for that unless you write on lowlevel ... keyCode is the same for both (it is 17)
Just You can use e.ctrlKey as a way to determine if the control key was pressed.
However I read around and found one answer mentioning you could do that in IE but I did not try it from my side
you can use e.originalEvent.location instead of the global event.location
$(document).ready(function(){
$("html").keydown(function(e) {
if (e.ctrlKey) {
if (e.originalEvent.location === 1) console.log('left ctrl');
if (e.originalEvent.location === 2) console.log('right ctrl');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
below is your answer for three mouse keyup events. rest for mousewheel you should ask again:
/*
1 = Left Mousebutton
2 = Centre Mousebutton
3 = Right Mousebutton
*/
$(document).mousedown(function(e) {
if (e.which === 3) {
/* Right Mousebutton was clicked! */
alert("right key code 3");
}
else if(e.which === 2) {
alert("Centre key code 2");
}
else if(e.which === 1) {
alert("Left key code 1");
}
});
you can use this:
$('#inputboxinput').bind('keypress', function(e) {
if(e.keyCode==13){
// Enter pressed... do anything here...
}
});
the cross-browser way:
if (!event.which && ((event.charCode || event.charCode === 0) ? event.charCode: event.keyCode)) {
event.which = event.charCode || event.keyCode;
}

How to retrieve keyCode and charCode from a jQuery event object?

The javascript event object offers keyCode() and charCode() methods such that charCode() returns 0 for keys that don't cause a character to be displayed like enter, key up, key down, delete, backspace, etc.
I want to check for exactly these characters inside a jQuery keypress event callback, but the jQuery event object doesn't give me access to the mentioned methods.
Can I retrieve the js event object from the jQuery one ?
$('#yourid').bind('keypress', function(e) {
var keycode= (e.keyCode ? e.keyCode : e.which);
if(keycode == 13){
// Enter pressed... do anything here...
}else if(keycode == 46){// delete
}else if(keycode == 8){ // backspace
}
});
Explorer doesn't fire the keypress event for delete, end, enter, escape, function keys, home, insert, pageUp/Down and tab.
If you need to detect these keys, do yourself a favour and search for their keyCode onkeydown/up, and ignore both onkeypress and charCode.
Key code lists are available all over the internet though here is the heavy lifting done for you without depending on any frameworks...
if (window.addEventListener) {document.addEventListener('keydown',keyPressed,false);}
else {document.attachEvent('onkeydown',keyPressed);}
function keyPressed(evt)
{
var e = evt || event;
var key = e.which || e.keyCode;
if (!powerKeysEnabled) return;
if (showmeallcodes) {alert( key); return;}
switch (key)
{
case 77:// M
alert('m key pressed');
break;
case 76://L
alert('L key pressed');
break;
}
}

How to listener the keyboard type text in Javascript?

I want to get the keyboard typed text, not the key code. For example, I press shift+f, I get the "F", instead of listen to two key codes. Another example, I click F3, I input nothing. How can I know that in js?
To do it document-wide, use the keypress event as follows. No other currently widely supported key event will do:
document.onkeypress = function(e) {
e = e || window.event;
var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
if (charCode) {
alert("Character typed: " + String.fromCharCode(charCode));
}
};
For all key-related JavaScript matters, I recommend Jan Wolter's excellent article: http://unixpapa.com/js/key.html
I use jQuery to do something like this:
$('#searchbox input').on('keypress', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) {
//Enter keycode
//Do something
}
});
EDIT: Since you're not binding to text box use:
$(window).on('keypress', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) {
//Enter keycode
//Do something
}
});
http://docs.jquery.com/Main_Page
You can listen for the onkeypress event. However, instead of just examining either the event.keyCode (IE) or event.which (Mozilla) property which gives you the key code, you need to translate the key code using String.fromCharCode().
A good demo is at Javascript Char Codes (Key Codes). View the source and look for the displayKeyCode(evt) function.
Additional references: w3schools - onkeypress Event and w3schools - JavaScript fromCharCode() method.
This is too complicated to answer quickly. This is what I use as the definitive reference for keyboard handling. http://unixpapa.com/js/key.html

Categories

Resources