I want to detect when the Alt/Option key and any other key are both pressed down simultaneously in a textarea on Mac. For example, I want to check for Alt/Option + 'h':
HTML
<textarea onkeydown="myFunction(event);"></textarea>
JavaScript
function myFunction(e) {
if (e.altKey && e.key=="h") {
// Do something here
}
}
The function works if I use Control instead of Alt. How can I get this to work with Alt on Mac?
JSFiddle
You can do this by directly ASCII value e.keyCode === 65 instead of checking by e.key == 'A'
function myFunction(e)
{
if ( e.altKey && e.keyCode === 65) //it check both altKey + 'A' or 'a'
{
//do something
}
}
i just did this for alt + a press. but you can do with any key by getting it's ASCII values
JsFiddle link for demo
Related
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" />
I'm trying to make a simple script. When a user presses a certain key, a character will be added to the value of a textarea. For example (this isn't my case), say the user presses the Alt + Enter keys. When they do so, I'd like to add a character onto the already existing text in the text field.
So, my code would be:
function doc_keyUp(e) {
if (e.altKey && e.keyCode == 13) {
*insert character into textarea*
}
}
document.addEventListener('keyup', doc_keyUp, false);
The code itself works fine- however, I'm unsure about how to insert the character. Any help is appreciated!
Just for reference, I'm attempting to create a simple phonetic keyboard for Ukrainian. You can type an English letter, and the Ukrainian counterpart shows up. Look at http://ua.translit.cc to better understand what I'm saying.
function doc_keyUp(e) {
if (e.altKey && e.keyCode == 13 || e.keyCode == 65) {
document.getElementById("area").value += "123";
}
}
function validateKey(e){
// here can be whatever keys
if (e.keyCode >= 65 && e.keyCode <= 90 || e.keyCode >= 97 && e.keyCode <= 122) return false;
}
document.addEventListener('keyup', doc_keyUp, false);
<textarea id="area" onKeyPress="return validateKey(event)">ABC</textarea>
Updated to validate some key in the entry of textarea.
You can just add the text to the value of the textarea.
function doc_keyUp(e) {
if (e.altKey && e.keyCode == 13) {
textarea.text += value
}
}
document.addEventListener('keyup', doc_keyUp, false);
I want to focus into a text box when ever be user press 'S' keyword in keyboard. But the problem is that 'S' keyword also typed in text box (this only happens in chrome). How I can do this here is my code.
$(document).keypress(function(event){
if(document.getElementById('search')!==null)
{
if(event.which==115 && event.target.nodeName=='BODY') // WHEN USER PRESS 'S' KEYWORD IN KEYBOARD ONLY
{
$('#search').focus();
}
}
});
Use event.preventDefault()
$(document).keypress(function(event){
if($('#search').length)
{
console.log(1);
if(event.which==115 && event.target.nodeName=='BODY') // WHEN USER PRESS 'S' KEYWORD IN KEYBOARD ONLY
{
event.preventDefault();
$('#search').focus();
}
}
});
you can also try
(event.keyCode==83) // 83 is keyCode for "s"
By using the event.preventDefault() you can restrict the keypress to update the textbox value. i have added event.which == 83 in case of caps is on.
$(document).keypress(function (event) {
if (document.getElementById('search') !== null) {
if ((event.which == 115 || event.which == 83) && event.target.nodeName == 'BODY') // WHEN USER PRESS 'S' KEYWORD IN KEYBOARD ONLY
{
$('#search').focus();
event.preventDefault();
}
}
});
Check the Demo for JSFiddler DEMO
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
}
});
I am trying to reproduce standard instant messenger behavior on TEXT area control:
enter works as send button. ctrl+enter as real enter.
$("#txtChatMessage").keydown(MessageTextOnKeyEnter);
function MessageTextOnKeyEnter(e)
{
if (!e.ctrlKey && e.keyCode == 13)
{
SendMessage();
return false;
}
else if(e.keyCode == 13)
{
$(this).val($(this).val() + "\n");
}
return true;
}
I have tried with both commented line and without. Not works. simple enter works as expected.
Any ideas how to add enter on ctrl+enter?
key code is not problem. they are detected correctly. so all if's works as expected. But appending new line works incorrectly (in FF, Chrome works correctly). So I need correct multibrowser way to insert new line symbol to textarea. If without adding string manually (by some event based on ctrl+enter) it will be better.
changing on keypress event has no effect. "\r\n" not helped.
test page located here
The following will work in all the major browsers, including IE. It will behave exactly as though the enter key had been pressed when you press ctrl-enter:
function MessageTextOnKeyEnter(e) {
if (e.keyCode == 13) {
if (e.ctrlKey) {
var val = this.value;
if (typeof this.selectionStart == "number" && typeof this.selectionEnd == "number") {
var start = this.selectionStart;
this.value = val.slice(0, start) + "\n" + val.slice(this.selectionEnd);
this.selectionStart = this.selectionEnd = start + 1;
} else if (document.selection && document.selection.createRange) {
this.focus();
var range = document.selection.createRange();
range.text = "\r\n";
range.collapse(false);
range.select();
}
}
return false;
}
}
wow what a pain in the ass. i've been playing with this for a while and i have to assume this is just IE being uncooperative. anyway, this is the best i could do this morning and it's super hacky, but maybe you can gain something from it.
explanation: i'm testing with ie8, a textarea element, and courier new. results may vary. ascii character 173 (0xAD) does not display a character, although it counts as a character when moving your cursor around. appending this char after you force a newline gets ie to move the cursor down. before the call to SendMessage we replace the extra char with nothing.
function MessageTextOnKeyEnter(e)
{
var dummy = "\xAD";
if (!e.ctrlKey && e.keyCode == 13)
{
var regex = new RegExp(dummy,"g");
var newval = $(this).val().replace(regex, '');
$(this).val(newval);
SendMessage();
return false;
}
else if(e.keyCode == 13)
{
$(this).val($(this).val() + "\n" + dummy);
}
return true;
}
if you try to do the replacement on every keystroke it's not going to work very well. you might be able to deal with this by white/blacklisting keys and find a method to put the cursor back in the text where it's supposed to go.
A few potential causes:
Define the function before you reference it.
Make sure you're binding the event in the document.ready event, so that the dom item exists when you reference it.
Change else (e.keyCode == 13) to else if (e.keyCode == 13).
Make sure this is a textarea, not an input[type=text].
Consider using keypress instead of keydown.
Some browsers will send keyCode == 10 instead of keyCode == 13 when using the ctrl modifier key (some browsers will send it even when you aren't using the ctrl modifier key).
My answer leads from Ian Henry's answer about keyCode == 10, which seems to be the case in IE (tested in 8 & 9). Check if you are dealing with a windows event and ket the key code.
$('#formID #textareaID').keypress(function(e) {
if(window.event) {
var keyCode = window.event.keyCode;
}
else {
var keyCode = e.keyCode || e.which;
}
if( (!e.ctrlKey && (keyCode == 13)) ) {
//do stuff and submit form
}
else if( (e.ctrlKey && (keyCode == 13)) || (keyCode == 10) ) {
//do stuff and add new line to content
}
});
You can check for the ctrl and alt as in
$(document).ready(function() {
$('#myinput').keydown(function(e) {
var keysare = 'key code is: ' + e.which + ' ' + (e.ctrlKey ? 'Ctrl' : '') + ' ' + (e.shiftKey ? 'Shift' : '') + ' ' + (e.altKey ? 'Alt' : '');
//alert(keysare);
$('#mycurrentkey').text(keysare);
return false;
});
});
See a working example here: http://jsfiddle.net/VcyAH/
If you can stick with Shift+Enter instead of Ctrl+Enter then the solution is trivial. You don't need any special code as Shift+Enter triggers a line break automatically. Just catch plain Enter to do the sending.