I have the following simple <textarea>
<textarea id="streamWriter" rows="1" cols="20" placeholder="Writer"></textarea>
Also I have the following jQuery/JavaScript code block:
$('textarea#streamWriter').keydown(function (e) {
if (e.keyCode == 13) {
if (e.ctrlKey) {
alert('ctrl enter - go down a line as normal return would');
return true;
}
e.preventDefault();
alert('submit - not your default behavior');
}
});
I'm trying to force the not to create a new line break on normal return keydown. But I want this behavior if Ctrl+Enter was typed instead.
This does detect the difference but is not forcing the behavior that I need.
If you've used Windows Live Messenger, I need the same textbox behavior. Enter to submit (In my case I will call a function but stop the textarea from going down a line) and Ctrl+Enter go down a line.
Solutions? Thanks.
Update:
$('textarea#streamWriter').keydown(function (e) {
if (e.keyCode == 13) {
if (e.ctrlKey) {
//emulate enter press with a line break here.
return true;
}
e.preventDefault();
$('div#writerGadgets input[type=button]').click();
}
});
The above does what I am trying to do. There is just the part to emulate enter press with a line break. Please let me know how to do this if you know.
Using keypress instead of keydown works a little better, however will not work with the Ctrl key; I switched to the shift key - jsfiddle.
Edit: As far as I can tell, you won't be able to use Ctrl key consistently cross browser because the browser uses it for it's own short-cuts. You would run into the same situation with the alt key.
Edit again: I have a solution that works with the Ctrl key - jsfiddle.
$('textarea#streamWriter').keydown(function (e) {
if (e.keyCode === 13 && e.ctrlKey) {
//console.log("enterKeyDown+ctrl");
$(this).val(function(i,val){
return val + "\n";
});
}
}).keypress(function(e){
if (e.keyCode === 13 && !e.ctrlKey) {
alert('submit');
return false;
}
});
Edit: This doesn't work 100%, it only works if you are not in the middle of text. Gonna have to work on a way to have the code work on text in the middle.
By the way... Why are you doing it this way? Wouldn't it be confusing to the user if they pressed enter to make a new line and the form all of a sudden submitted before they were ready?
Clear VanillaJS:
document.querySelector('#streamWriter').addEventListener('keydown', function (e) {
if (e.keyCode === 13) {
// Ctrl + Enter
if(e.ctrlKey) {
console.log('ctrl+enter');
// Enter
} else {
console.log('enter');
}
}
});
Kevin B's solution works well on Mac, but not on windows.
On windows, when ctrl +enter is pressed, the keyCode is 10 not 13.
Ctrl+Enter jQuery in TEXTAREA
Related
How do I go about capturing the CTRL + S event in a webpage?
I do not wish to use jQuery or any other special library.
Thanks for your help in advance.
An up to date answer in 2020.
Since the Keyboard event object has been changed lately, and many of its old properties are now deprecated, here's a modernized code:
document.addEventListener('keydown', e => {
if (e.ctrlKey && e.key === 's') {
// Prevent the Save dialog to open
e.preventDefault();
// Place your code here
console.log('CTRL + S');
}
});
Notice the new key property, which contains the information about the stroked key. Additionally, some browsers might not allow code to override the system shortcuts.
If you're just using native / vanilla JavaScript, this should achieve the results you are after:
var isCtrl = false;
document.onkeyup=function(e){
if(e.keyCode == 17) isCtrl=false;
}
document.onkeydown=function(e){
if(e.keyCode == 17) isCtrl=true;
if(e.keyCode == 83 && isCtrl == true) {
//run code for CTRL+S -- ie, save!
return false;
}
}
What's happening?
The onkeydown method checks to see if it is the CTRL key being pressed (key code 17).
If so, we set the isCtrl value to true to mark it as being activated and in use. We can revert this value back to false within the onkeyup function.
We then look to see if any other keys are being pressed in conjunction with the ctrl key. In this example, key code 83 is for the S key. You can add your custom processing / data manipulation / save methods within this function, and we return false to try to stop the browser from acting on the CTRL-S key presses itself.
document.onkeydown = function(e) {
if (e.ctrlKey && e.keyCode === 83) {
alert('hello there');
// your code here
return false;
}
};
You need to replace document with your actual input field.
DEMO
document.onkeydown = function(e) {
if (e.ctrlKey && e.keyCode === 83) {
alert('strg+s');
}
return false;
};
Some events can't be captured, since they are capture by the system or application.
Oops you wanted simultaneous, changed code to reflect your scenario
function iskeyPress(e) {
e.preventDefault();
if (e.ctrlKey&&e.keyCode == 83) {
alert("Combination pressed");
}
return false;//To prevent default behaviour
}
Add this to body
<body onkeyup="iskeypress()">
Mousetrap is a great library to do this (8,000+ stars on Github).
Documentation: https://craig.is/killing/mice
// map multiple combinations to the same callback
Mousetrap.bind(['command+s', 'ctrl+s'], function() {
console.log('command s or control s');
// return false to prevent default browser behavior
// and stop event from bubbling
return false;
});
Add Shortcuts JS library and do the following code :
<script src="js/libs/shortcut/shortcut.js" type="text/javascript"></script>
Then
shortcut.add("Ctrl+S", function() {
alert("لقد قمت بالصغط على مراقبة مع حرف السين");
});
I want to prevent the default event on key #93 (select, between alt gr and ctrl right on AZERTY keyboard).
This key open context menu like right click.
I tried :
$(document).off('keydown');
$(document).off('keyup');
$(document).off('keypress');
$(document).on('keypress', function(e){
if(e.keyCode == 93)
{
e.preventDefault();
return false;
}
});
$(document).on('keyup', function(e){
if(e.keyCode == 93)
{
e.preventDefault();
return false;
}
});
$(document).on('keydown', function(e){
if(e.keyCode == 93)
{
e.preventDefault();
return false;
}
});
Nothing works... I have always the contextmenu.
After checking for a while, I've been headed to another question similar to this one, but with a very different matter.
In any case, since the problem is the context menu, you don't even need jQuery for such, and the solution (despite it WON'T always work in firefox because the user may set it to disable such) is this one:
document.oncontextmenu = function (e) {
e.preventDefault();
return false;
}
fiddle:
http://jsfiddle.net/0kkm1vq0/3/
Works on chrome as well, and you won't need to use the keyboard listeners.
Reference: How to disable right-click context-menu in javascript
(which is really the same as key #93).
** note that this will disable the right click too **.
EDIT:
Not sure if this is cross-browser (the UPDATED code below seems to be working for both chrome and firefox, didn't try IE and others though), but the event fired by key #97 seems to be identified as 1, while the click seems to be identified as key 3, so you can just:
(function($){
if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
$(document).on('keyup', function(e) {
e.which == 93 && e.preventDefault();
});
}
else {
document.oncontextmenu = function (e) {
e.which == 1 && e.preventDefault();
}
}
})(jQuery);
http://jsfiddle.net/0kkm1vq0/10/
To disable JUST the key and not the right click.
How do I go about capturing the CTRL + S event in a webpage?
I do not wish to use jQuery or any other special library.
Thanks for your help in advance.
An up to date answer in 2020.
Since the Keyboard event object has been changed lately, and many of its old properties are now deprecated, here's a modernized code:
document.addEventListener('keydown', e => {
if (e.ctrlKey && e.key === 's') {
// Prevent the Save dialog to open
e.preventDefault();
// Place your code here
console.log('CTRL + S');
}
});
Notice the new key property, which contains the information about the stroked key. Additionally, some browsers might not allow code to override the system shortcuts.
If you're just using native / vanilla JavaScript, this should achieve the results you are after:
var isCtrl = false;
document.onkeyup=function(e){
if(e.keyCode == 17) isCtrl=false;
}
document.onkeydown=function(e){
if(e.keyCode == 17) isCtrl=true;
if(e.keyCode == 83 && isCtrl == true) {
//run code for CTRL+S -- ie, save!
return false;
}
}
What's happening?
The onkeydown method checks to see if it is the CTRL key being pressed (key code 17).
If so, we set the isCtrl value to true to mark it as being activated and in use. We can revert this value back to false within the onkeyup function.
We then look to see if any other keys are being pressed in conjunction with the ctrl key. In this example, key code 83 is for the S key. You can add your custom processing / data manipulation / save methods within this function, and we return false to try to stop the browser from acting on the CTRL-S key presses itself.
document.onkeydown = function(e) {
if (e.ctrlKey && e.keyCode === 83) {
alert('hello there');
// your code here
return false;
}
};
You need to replace document with your actual input field.
DEMO
document.onkeydown = function(e) {
if (e.ctrlKey && e.keyCode === 83) {
alert('strg+s');
}
return false;
};
Some events can't be captured, since they are capture by the system or application.
Oops you wanted simultaneous, changed code to reflect your scenario
function iskeyPress(e) {
e.preventDefault();
if (e.ctrlKey&&e.keyCode == 83) {
alert("Combination pressed");
}
return false;//To prevent default behaviour
}
Add this to body
<body onkeyup="iskeypress()">
Mousetrap is a great library to do this (8,000+ stars on Github).
Documentation: https://craig.is/killing/mice
// map multiple combinations to the same callback
Mousetrap.bind(['command+s', 'ctrl+s'], function() {
console.log('command s or control s');
// return false to prevent default browser behavior
// and stop event from bubbling
return false;
});
Add Shortcuts JS library and do the following code :
<script src="js/libs/shortcut/shortcut.js" type="text/javascript"></script>
Then
shortcut.add("Ctrl+S", function() {
alert("لقد قمت بالصغط على مراقبة مع حرف السين");
});
I want to have a chat box (textarea) where if user press Enter then it should submit the chat, and if user press Shift+Enter then it should enter in a new line.
I tried something but not able to figure out the exact keyup or keydown thing. The code I'm using at the moment is:
$("textarea").keydown(function(e){
if (e.keyCode == 13 && !e.shiftKey)
{
e.preventDefault();
}
});
jsFiddle
Also I want to get the \n in place when Enter+Shift key is pressed.
EDIT
Issue with my code is:-
When i am check the content on client using using alert then it shows the next line. But when i am posting it my rails back end. Then its just a simple string. No new line thing is there.
This is how i am sending chats to rails server.
$.post("/incomingchat", { body:$("#chat_" + group_id).val() },
function(data){
// do something..
});
I've answered this before. It's a little tricky if the caret is not at the end of the textarea:
How do I detect "shift+enter" and generate a new line in Textarea?
$("textarea").keydown(function(e)
{
if (e.keyCode == 13)
{
if (e.shiftKey) {
$(this).val( $(this).val() + "\n" );
}
else {
submitTheChat();
}
}
});
Consider using the keypress event instead. If you run the code in jsfiddle, you'll see that a new line is not added when you press enter.
$("textarea").keypress(function(e){
if (e.keyCode == 13 && !e.shiftKey)
{
e.preventDefault();
//now call the code to submit your form
alert("just enter was pressed");
return;
}
if (e.keyCode == 13 && e.shiftKey)
{
//this is the shift+enter right now it does go to a new line
alert("shift+enter was pressed");
}
});
I’m working with basic HTML <input type="text"/> text field with a numeric value.
I’m adding JavaScript event keyup to see when user presses arrow up key (e.which == 38) – then I increment the numeric value.
The code works well, but there’s one thing that bugs me. Both Safari/Mac and Firefox/Mac move cursor at the very beginning when I’m pressing the arrow up key. This is a default behavior for every <input type="text"/> text field as far as I know and it makes sense.
But this creates not a very aesthetic effect of cursor jumping back and forward (after value was altered).
The jump at the beginning happens on keydown but even with this knowledge I’m not able to prevent it from occuring. I tried the following:
input.addEventListener('keydown', function(e) {
e.preventDefault();
}, false);
Putting e.preventDefault() in keyup event doesn’t help either.
Is there any way to prevent cursor from moving?
To preserve cursor position, backup input.selectionStart before changing value.
The problem is that WebKit reacts to keydown and Opera prefers keypress, so there's kludge: both are handled and throttled.
var ignoreKey = false;
var handler = function(e)
{
if (ignoreKey)
{
e.preventDefault();
return;
}
if (e.keyCode == 38 || e.keyCode == 40)
{
var pos = this.selectionStart;
this.value = (e.keyCode == 38?1:-1)+parseInt(this.value,10);
this.selectionStart = pos; this.selectionEnd = pos;
ignoreKey = true; setTimeout(function(){ignoreKey=false},1);
e.preventDefault();
}
};
input.addEventListener('keydown',handler,false);
input.addEventListener('keypress',handler,false);
I found that a better solution is just to return false; to prevent the default arrow key behavior:
input.addEventListener("keydown", function(e) {
if (e.key === 'ArrowUp' || e.key === 'ArrowDown') return false;
}, false);
Actually, there is a better and simpler method to do this job.
$('input').bind('keydown', function(e){
if(e.keyCode == '38' || e.keyCode == '40'){
e.preventDefault();
}
});
Yes, it is so easy!
In my case (react) helped:
onKeyDown = {
(e) => {
if (e.key === 'ArrowUp' || e.key === 'ArrowDown') e.preventDefault();
}
}
and onKeyUp was fully functional
I tested the code and it seems that it cancels the event but if you don't press the arrow for very short time - it fires keypress event and that event actually moves cursor. Just use preventDefault() also in keypress event handler and it should be fine.
Probably not. You should instead seek for a solution to move the cursor back to the end of the field where it was. The effect would be the same for the user since it is too quick to be perceived by a human.
I googled some and found this piece of code. I can't test it now and it is said to not to work on IE 6.
textBox.setSelectionRange(textBox.value.length, textBox.value.length);