Prevent default behavior in text input while pressing arrow up - javascript

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);

Related

How to move caret «home» or «end» use fn+arrow key JavaScript

How to repeat behaviour CMD+arrowLeft (Home) and CMD+arrowRight (End) for fn+arrowLeft and fn+arrowRight as well.
Please write code if existed another approach to move caret (cursor) to the begin or to the end of input field use combination of keys. I use MacOs.
36 - event.key for fn+arrowLeft
35 - event.key for fn+arrowRight
const handleKey = (e) => {
if (e.metaKey || e.altKey || e.ctrlKey) {
e.preventDefault();
}
if (e.key === 'Home') {
// code here
}
if (e.key === 'End') {
// code here
}
};
<input type="text" onkeydown="handleKey()">
As alternative way but doesn’t cover my need:
Set keyboard caret position in html textbox
I assumed that good way but don’t know how use right KeyboardEvent object:
how to set keycode value while triggering keypress event manually in pure javascript?

how to unbind/prevent context menu by keyboard (key #93) with FF?

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.

the shift key is just ignored after another key has been depressed, poor shift key. How do I detect when it is released?

I have a text input, that presently goes transparent when a user presses shift (keydown) and binds a listener for the shift key going up
ie.
$('#foo').keydown(function(){
if(event.which==16){
//make #foo transparent
$(this).keyup(function(){
if(event.which==16){
//return #foo to its former glory
$(this).unbind('keyup');
}
});
};
})
This works fine when no characters are pressed in the interim between depressing and releasing the shift key. The problem is that when shift is down and another character is pressed, the shift key seems to have been completely forgotten about. When the shift key is released, no keyup fires.
I tried triggering a 'fake' keydown with the .which property set to 16, to nudge it in the right direction after other characters are pressed, but to no avail.
Any suggestions would be greatly appreciated!
While pressing shift, it will continuously trigger keydown events until you release it, so your example will bind as many keyup handlers as there are keydown events triggered. This will most likely cause all kind of weird problems.
Instead, bind both keydown and keyup to the same handler and do your magic in there:
$("#foo").on("keydown keyup", function (e) {
if (e.which === 16) {
if (e.type === "keydown") {
// make #foo transparent
} else {
// return #foo to its former glory
}
}
});
See test case on jsFiddle.
However, if you lose focus of the input while pressing shift and then release, it will not work as expected. One way to solve it is to bind to window instead:
var $foo = $("#foo");
var shiftPressed = false;
$(window).on("keydown keyup", function (e) {
if (e.which === 16) {
shiftPressed = e.type === "keydown";
if (shiftPressed && e.target === $foo[0]) {
$foo.addClass("transparent");
} else {
$foo.removeClass("transparent");
}
}
});
$foo.on("focus blur", function (e) {
if (e.type === "focus" && shiftPressed) {
$foo.addClass("transparent");
} else {
$foo.removeClass("transparent");
}
});
See test case on jsFiddle.

How do I capture a CTRL-S without jQuery or any other library?

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("لقد قمت بالصغط على مراقبة مع حرف السين");
});

textarea control - custom behavior enter/ctrl+enter

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

Categories

Resources