When i click on "enter" I call a function. Within this function I do the following:
var key = event.keyCode;
if (key == 13 && !event.shiftKey)
I am using this function on a textarea.
When I press enter everything works except one thing: A line break is made within the textarea which should be prevented. How to avoid?
This is how you can do it:
function(event) {
event.preventDefault();
var key = event.keyCode;
if (key == 13 && !event.shiftKey) ...
}
event.preventDefault() also works for links and in any other case you want to prevent the default action of an event.
Another important function sometimes is event.stopPropagation().
More information here:
https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
and here: https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation
Related
I have a custom dropdown in angular JS which is a combination of textbox and list. Here on keydown event I am checking the key code and getting the char from String.fromCharCode(keyCode). and apply the style(highlighted) for the typed character from the list. This works fine for a single character.
for example in my list iam having {'india','ireland','egypt','england','nigeria'}
Here my code works if I type e it will point to the first country Egypt. My requirement is if I type en continuously it should highlight England, but this is not happening. As soon as I type n it will highlight Nigeria. because the keydown event is immediately firing and it is selecting for next char entered.
elem.on('keydown.ddl', function (e) {
case (keyCode >= 65 && keyCode <= 90):
var keyChar = String.fromCharCode(keyCode); //this give
//here i am changing the style
break;
});
I have an input on one of my pages that has listeners on it that perform formatting on values entered into it.
The field only allows certain input(numerical as well as certain other characters), which is controlled with a keypress and a keyup listener. The keypress prevents illegal input, and the keyup performs formatting(and also checks input, in case the user pasted something into the field instead of typing).
It worked fine in Chrome and IE (back to IE8, I don't care about anything earlier), but in Firefox I was unable to use the tab key, arrow keys, backspace, and was unable to copy or paste using ctrl+c/v
After some investigation I found that the problem lies with this listener:
$(this).keypress(function(e)
{
consumeIllegalFloatKeyPress(e);
});
In IE and Chrome, keys like tab, arrows and backspace weren't even triggering the listener, and keypresses like v and c would not trigger it either, when used with the ctrl key. However, in FF it picks up all the keypresses, which resulted in
consumeIllegalFloatKeyPress(e);
getting called, and finding that the keypresses were illegal.
The fix was easy enough - I have an array of legal inputs that is used to check what should be allowed, so I just added the charCodes for v and c, and put in a key for the ctrlKey as well.
What I am confused about is why these are being handled differently in different browsers? I thought that, since it was all javascript, that it would handle the CTRL key the same across all browsers.
If anyone has any information on this, or knows of somewhere I can read up more on it, I'd be very interested and grateful!
Try the below solution. This works perfect for my issue
function captureKeyPress(e) {
var keycode = (e.keyCode ? e.keyCode : e.which);
var ctrlKeyPressed = e.ctrlKey;
var key = e.which;
switch(e.key){
case "c": //right arrow key
if (!ctrlKeyPressed) {
alert('C pressed');
}
break;
}
}
window.addEventListener("keypress", captureKeyPress);
Let's have a look at official documentation:
jQuery keypress listener
2 important things can be read here:
Note: as the keypress event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms.
And:
This method is a shortcut for .on( "keypress", handler ) in the first two variations, and .trigger( "keypress" ) in the third.
Let's have a look at what the Javascript documentation says about keypress:
javascript keypress event
After a few clicks we see a nice table on this page
The table shows which browsers accepts certain keys, like non-printable keys (arrow keys, control, page down, ...) and which don't.
The final answer to your question is: if there is no set standard for something (like the keypress event), then browsers will do whatever they feel like doing. For Google chrome this means it allows CTRL + V, where Mozilla Firefox filters it.
Please try this solution:
$(document).on("keypress", this, function (e) {
var keycode = (e.keyCode ? e.keyCode : e.which);
/* Example */
if (keycode === 27) {
alert("Escape key");
}
});
...and you can enable or disable keys what you whant.
I will give you one my function for this:
FUNCTION:
$.fn.pKey = function (key, callback) {
var key=key;
return this.each(function () {
$(document).on("keypress", this, function (e) {
var keycode = (e.keyCode ? e.keyCode : e.which);
if (keycode === key) {
callback.call(this, e);
};
});
});
};
EXAMPLE:
$("#my-div").pKey(17,function (e) {
/* disable CTRL*/
e.preventDefault();
})
I have setup an event listener:
editor.addEventListener('keydown', function(e) {
if (e.shiftKey === false) {
alert(String.charFromCode(e.keyCode).toLowerCase());
}
else {
alert(String.charFromCode(e.keyCode));
}
}, false);
When the user presses 2 along with shift, how do I know if I should output (#) or (")? Each users' character mapping is different per locale.
Use the keypress event instead. It will reliably (barring a few edge cases) detect the character typed.
There are a few browser oddities (such as some non-printable keys generating keypress events with key codes in the which property in some browsers) that prevent the following example from being 100% perfect which you can read about in great detail at the definitive page on JavaScript key events.
Example:
editor.addEventListener('keypress',
function(e)
{
var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
alert( String.charFromCode(charCode) );
},
false);
Short answer: you really can't. Use a keypress or keyup listener, and compare the old (textbox, I assume?) value to the new one to see what actually happened.
I have a function that is triggered by the onkeydown event of a textbox. How can I tell if the user has hit either the backspace key or the del key?
Try this:
document.addEventListener("keydown", KeyCheck); //or however you are calling your method
function KeyCheck(event)
{
var KeyID = event.keyCode;
switch(KeyID)
{
case 8:
alert("backspace");
break;
case 46:
alert("delete");
break;
default:
break;
}
}
event.key === "Backspace" or "Delete"
More recent and much cleaner: use event.key. No more arbitrary number codes!
input.addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; ES6+
if (key === "Backspace" || key === "Delete") {
return false;
}
});
Mozilla Docs
Supported Browsers
Nowadays, code to do this should look something like:
document.getElementById('foo').addEventListener('keydown', function (event) {
if (event.keyCode == 8) {
console.log('BACKSPACE was pressed');
// Call event.preventDefault() to stop the character before the cursor
// from being deleted. Remove this line if you don't want to do that.
event.preventDefault();
}
if (event.keyCode == 46) {
console.log('DELETE was pressed');
// Call event.preventDefault() to stop the character after the cursor
// from being deleted. Remove this line if you don't want to do that.
event.preventDefault();
}
});
although in the future, once they are broadly supported in browsers, you may want to use the .key or .code attributes of the KeyboardEvent instead of the deprecated .keyCode.
Details worth knowing:
Calling event.preventDefault() in the handler of a keydown event will prevent the default effects of the keypress. When pressing a character, this stops it from being typed into the active text field. When pressing backspace or delete in a text field, it prevents a character from being deleted. When pressing backspace without an active text field, in a browser like Chrome where backspace takes you back to the previous page, it prevents that behaviour (as long as you catch the event by adding your event listener to document instead of a text field).
Documentation on how the value of the keyCode attribute is determined can be found in section B.2.1 How to determine keyCode for keydown and keyup events in the W3's UI Events Specification. In particular, the codes for Backspace and Delete are listed in B.2.3 Fixed virtual key codes.
There is an effort underway to deprecate the .keyCode attribute in favour of .key and .code. The W3 describe the .keyCode property as "legacy", and MDN as "deprecated".
One benefit of the change to .key and .code is having more powerful and programmer-friendly handling of non-ASCII keys - see the specification that lists all the possible key values, which are human-readable strings like "Backspace" and "Delete" and include values for everything from modifier keys specific to Japanese keyboards to obscure media keys. Another, which is highly relevant to this question, is distinguishing between the meaning of a modified keypress and the physical key that was pressed.
On small Mac keyboards, there is no Delete key, only a Backspace key. However, pressing Fn+Backspace is equivalent to pressing Delete on a normal keyboard - that is, it deletes the character after the text cursor instead of the one before it. Depending upon your use case, in code you might want to handle a press of Backspace with Fn held down as either Backspace or Delete. That's why the new key model lets you choose.
The .key attribute gives you the meaning of the keypress, so Fn+Backspace will yield the string "Delete". The .code attribute gives you the physical key, so Fn+Backspace will still yield the string "Backspace".
Unfortunately, as of writing this answer, they're only supported in 18% of browsers, so if you need broad compatibility you're stuck with the "legacy" .keyCode attribute for the time being. But if you're a reader from the future, or if you're targeting a specific platform and know it supports the new interface, then you could write code that looked something like this:
document.getElementById('foo').addEventListener('keydown', function (event) {
if (event.code == 'Delete') {
console.log('The physical key pressed was the DELETE key');
}
if (event.code == 'Backspace') {
console.log('The physical key pressed was the BACKSPACE key');
}
if (event.key == 'Delete') {
console.log('The keypress meant the same as pressing DELETE');
// This can happen for one of two reasons:
// 1. The user pressed the DELETE key
// 2. The user pressed FN+BACKSPACE on a small Mac keyboard where
// FN+BACKSPACE deletes the character in front of the text cursor,
// instead of the one behind it.
}
if (event.key == 'Backspace') {
console.log('The keypress meant the same as pressing BACKSPACE');
}
});
In your function check for the keycode 8 (backspace) or 46 (delete)
Keycode information
Keycode list
not sure if it works outside of firefox:
callback (event){
if (event.keyCode === event.DOM_VK_BACK_SPACE || event.keyCode === event.DOM_VK_DELETE)
// do something
}
}
if not, replace event.DOM_VK_BACK_SPACE with 8 and event.DOM_VK_DELETE with 46 or define them as constant (for better readability)
I need to change in a text input the character '.' to ',' while typing.
In IE I change the keyCode event property in the keypress event, like this
document.getElementById('mytext').onkeypress =
function (evt) {
var e = evt || window.event;
if (e.keyCode && e.keyCode==46)
e.keyCode = 44;
else if (e.which && e.which==46) {
e.which = 44;
}
};
but it seemes that in Firefox it's impossible to change characters typed in key events.
Any suggestions?
Try this. It works on all browsers:
window.onload = function () {
var input = document.getElementById("mytext");
input.onkeypress = function () {
var evt = arguments[0] || event;
var char = String.fromCharCode(evt.which || evt.keyCode);
// Is it a period?
if (char == ".") {
// Replace it with a comma
input.value += ",";
// Cancel the original event
evt.cancelBubble = true;
return false;
}
}
};
Update: Pier Luigi pointed out a problem with the above. It doesn't take care of the caret position not being at the end of the text. It will append the command to the end even if you're inserting some text to the value.
The solution would be, instead of appending a comma, to simulate a keypress event for the comma key. Unfortunately the way dispatching of synthetic events work in different browsers seems to show a lot of variety and isn't an easy feat. I'll see if I can find a nice and generic method for it.
Assume that all properties in an Event object are immutable. The DOM spec doesn't address what happens when you change those values manually.
Here's the logic you need: listen for all key events. If it's a period, suppress the event, and manually add the comma at the cursor position. (Here's a code snippet for inserting arbitrary text at the cursor position.)
You'd suppress the event in Firefox by calling event.preventDefault(); this tells the browser not to go ahead with the default action associated with this event (in this case, typing the character). You'd suppress the event in IE by setting event.returnValue to false.
If it's not a period, return early from your handler.
Technically you just want to replace all dots with commas.
document.getElementById('mytext').onkeyup = function(){
this.value = this.value.replace('.', ',');
}
If I look at the official Document Object Model Events document, mouse events fields are defined as read-only. Keyboard events are not defined there, I suppose Mozilla followed this policy for them.
So basically, unless there is some smart trick, you cannot alter an event the way you want. You probably have to intercept the key and insert the char (raw or translated) where the caret is, the way JS HTML editors do.
Does this really need to be done on the fly? If you are collecting the information to be posted to a form or submitted to a database, would it not be better to modify the data once it was submitted? That way the user never sees the confusing change.
This is possible now by intercepting and cancelling the default keydown event and using HTMLInputElement.setRangeText to insert your desired character. This would look something like this:
document.addEventListener('keydown', $event => {
if($event.code === 'Period'){
$event.preventDefault();
let inputEl = document.querySelector("#my-input");
inputEl.setRangeText(
',',
inputEl.selectionStart,
inputEl.selectionEnd,
"end"
);
}
})
setRangeText will insert text at the cursor position in a given input. The "end" string as the last argument sets the cursor to the end of the inserted content.
More info here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setRangeText