e.key is not supported in most browser - javascript

In a event listener I am using e.key, but it seems it is not supported by many older browsers.
From https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode and https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/which I can read that e.keyCode and e.which are deprecated in favor of e.key, so I want to use e.key, but what should I do when some browsers are not supporting it?
Should I use
const key = e.key || String.fromCharCode(e.keyCode);
It just seems that they don't give me the same results if the key is, for instance, a comma.

You use whichever is supported by checking them all, starting with the preferred e.key which will be supported by all browsers in time
if (e.key) {
var key = e.key;
} else {
var code = e.which || e.keyCode;
var key = String.fromCharCode(code);
}
They should return the same character
document.getElementById('test').addEventListener('keypress', function(e) {
var code = e.which || e.keyCode;
var key = String.fromCharCode(code);
console.log(key, e.key)
});
<p>Type in the input !</p>
<input id="test">
Note that keyup and keydown events will return different keycodes for certain keys.

I tried implementing e.key in my application because I read on MDN that e.keyCode and e.which are both deprecaenter code hereted as well. However, all I see anywhere is still implementations of e.keyCode || e.which, and that exact code still works everywhere and well for me. MDN does not provide any solution or viable implementation for e.key and I see no key codes anywhere either. I say the documentation is wrong. And as stated here, e.key is NOT the same as e.keyCode or e.which. I would like to know what actually is supposed to be replacing e.keyCode or e.which. I am using it for example, in a keydown event. e.key breaks my code. This is the code:
[...inputs].forEach(input => input.addEventListener('keydown', (e) => {
console.log(Array.isArray([...inputs]))
console.log([...inputs])
const chord = e.keyCode || e.which
if (chord === 8) {
e.preventDefault()
e.currentTarget.value = ''
heading1.innerHTML = `User Registration Form`;
heading1.style.color = `#228b22`;
}
}))
And this is the link to the live application:
User Registration Form Using JS Constraint Validation API

Related

jQuery composition event is undefined

I do not want users to enter numbers or special character within a name input field and I have achieved this with the following code:
jQuery(document).ready(function() {
jQuery(".txtOnly").keypress(function(e) {
var key = e.keyCode;
if(key < 97 || key > 122) {
e.preventDefault();
}
});
});
But I want to avoid numbers and special characters from microsoft IME Japanese Keyboard as well though the keypress does not work so I am using a jQuery composition event which is working but it always returns undefined, so I am unable to get the key code or the value this way.
My Code:
jQuery(document).ready(function() {
jQuery(".txtOnly").on('compositionupdate', function(e) {
var keyCode = e.keyCode;
alert(keyCode); //Undefined
console.log(e.data); //Undefined
});
});
How I can get the keycode using a composition event or what other solution can I use for the Microsoft IME Japanese Keyboard?

Javascript, window.event, form validation

This was an example from our prof and my HTML is rusty so I'm not sure exactly what is going on.
For the form input:
<input type="text" name="widgets" id="widgets" size="2" value="0" onchange="calc();" onkeypress="return isNumberInput(this, event);" />
For the Javascript:
function isNumberInput(field, event)
{
var key, keyChar;
if (window.event)
key = window.event.keyCode;
else if (event)
key = event.which;
else
return true;
// Check for special characters like backspace
if (key == null || key == 0 || key == 8 || key == 13 || key == 27)
return true;
// Check to see if it.s a number
keyChar = String.fromCharCode(key);
if (/\d/.test(keyChar))
{
window.status = "";
return true;
}
else
{
window.status = "Field accepts numbers only.";
return false;
}
Can someone explain what is going on? I'm not too familiar with window.event, event.which, wondow.event.keyCode, etc. I don't really understand the logic. TIA!
var key, keyChar; // declare variable to be used
if (window.event) // window.event Microsoft uses window.event. Does it exist? If so continue
key = window.event.keyCode; // Microsoft uses window.event.keyCode to get the key the was pressed
else if (event) // other modern browsers will create an event object for you to use
key = event.which; // event.which is the key that was pressed
else // else we can't get to the key maybe this is a full text browser? Anyways, no good exit function
return true;
Basically, this code prevents the user from entering anything except a digit in the text field. The function returns true to allow the user to enter the keystroke, and false to prevent it. Additionally, special characters are allowed through as well.
As far as the part that is confusing you, this is really old code, designed for older versions of Netscape and IE. With modern browsers, you could just use event.keyCode, but Netscape used to use event.which, and IE used to require you to use window.event. Modern browsers hide the status bar too, making the window.status lines useless.

Add An Even listener For any letter keys pressed?

I am wondering how to create an event listener, so that when any of the character keys are pressed a form pops up and the first input is in focus and is receiving the input, sort of like the just type search style for the webOS 2.0 operating system, but for a contact form. Is there anyway to do so? In case your not familiar here is a link to the webos just type feature
http://www.youtube.com/watch?v=ixPsB7-tVGo
I don't know if you can only subscribe to letter keys.
Your best bet would be to use jQuery to subscribe to .keydown() / .keyup() and check the keycode of the event to see which letter it is. If it's not a letter, don't do anything.
Like this:
$('#target').keydown(function(event) {
if (event.keyCode >= 65 && event.keyCode <= 90) { // if a letter pressed
// play that funky music.
}
});
More on $.keydown.
List of key codes.
Use the keypress event for anything character related. keydown and keyup cannot be used reliably for this purpose. The following is adapted from my answer to a related recent question:
function isCharacterKeyPress(evt) {
if (typeof evt.which == "undefined") {
// This is IE, which only fires keypress events for printable keys
return true;
} else if (typeof evt.which == "number" && evt.which > 0) {
// In other browsers except old versions of WebKit, evt.which is
// only greater than zero if the keypress is a printable key.
// We need to filter out backspace and ctrl/alt/meta key combinations
return !evt.ctrlKey && !evt.metaKey && !evt.altKey && evt.which != 8;
}
return false;
}
var input = document.getElementById("your_input_id");
input.onkeypress = function(evt) {
evt = evt || window.event;
if (isCharacterKeyPress(evt)) {
// Do your stuff here
alert("Character!");
}
};

Detect printable keys

I need to detect whether the key which has just been pressed is a printable key, like a character, possibly accented, a number, a space, a punctuation symbol and so on, or a non printable key, like ENTER, TAB or DELETE.
Is there a reliable way to do this in Javascript, other than listing all non printable keys and hope not to forget some?
Luckily, this task is much easier in modern browsers. You can now use KeyboardEvent.key to detect a printable key via its length.
test.onkeydown = e => {
let isPrintableKey = e.key.length === 1;
alert(`Key '${e.key}' is printable: ${isPrintableKey}`);
}
<input id="test">
Besides that, you can also detect any other keys from the list, like Enter, Delete, Backspace, Tab, etc.
This method is much more reliable simply because unlike event.which, event.key is already standardized.
I answered a similar question yesterday. Note that you have to use the keypress event for anything character-related; keydown won't do.
I would argue that Enter is printable, by the way, and this function considers it to be. If you disagree, you can amend it to filter out keypresses with the which or keyCode property of the event set to 13.
function isCharacterKeyPress(evt) {
if (typeof evt.which == "undefined") {
// This is IE, which only fires keypress events for printable keys
return true;
} else if (typeof evt.which == "number" && evt.which > 0) {
// In other browsers except old versions of WebKit, evt.which is
// only greater than zero if the keypress is a printable key.
// We need to filter out backspace and ctrl/alt/meta key combinations
return !evt.ctrlKey && !evt.metaKey && !evt.altKey && evt.which != 8;
}
return false;
}
var input = document.getElementById("your_input_id");
input.onkeypress = function(evt) {
evt = evt || window.event;
if (isCharacterKeyPress(evt)) {
// Do your stuff here
alert("Character!");
}
});
If you need to identify printable key just for change detection as user change the input, you could use oninput event.
let isPrintableKey = event.key.length === 1 || event.key === 'Unidentified';
If you do not include: || event.key === 'Unidentified' your code will not work on mobile browsers.

Converting keystrokes gathered by onkeydown into characters in JavaScript

I try to convert keystrokes into chracters.
In other question someone recommand to use the onkeydown function because onkeypress gets handeled differently by different characters.
I don't know how to handle special chracters like ยด ` ' ( ) that might be different in different keyboards around the world.
For keys that have printable character equivalents, you should use the keypress event because you can retrieve character codes from the keypress event, which is generally not possible for keyup and keydown events.
The event properties you need are which and keyCode - pretty much all browsers have one or both of these, though IE muddies the waters by using keyCode for the character code while some other browsers return a (different) key code. Most non-IE browsers also have charCode but it seems all such browsers also have which, so charCode is never needed. A simple example:
document.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
var charStr = String.fromCharCode(charCode);
alert(charStr);
};
Here is a useful reference page.
document.onkeydown = checkKey;
function checkKey(e) {
e = e || window.event;
document.getElementById("label").style.display = "none";
if (e.keyCode == '65') {
//a
var lx = document.getElementById('location');
typeIt("a");
}
else if (e.keyCode == '66') {
//b
var lx = document.getElementById('location');
typeIt("b");
}
else if (e.keyCode == '67') {
//c
var lx = document.getElementById('location');
typeIt("c");
}
}
This should successfully convert the key code you press into a string letter, which you can use in a bigger function. It takes more time, but I found it is highly compatible with most browsers and keyboards (whatever the language may be.) I used this code in a text editor project which would be distributed to friends in several countries, so I am certain it will work. Note: the function above only includes the letters "A", "B", and "C".

Categories

Resources