Been trying to search around for the most efficient way to override a default keydown event in VanillaJS. In my case specifically, I'm trying to override the default event of the "backspace" key and give it the functionality of a left-arrow key.
I figured out how to use event.preventDefault() to stop the default event from happening, with this code:
document.querySelector(/* Target selector */).onkeydown = checkKey;
function checkKey(event) {
let which = event.which;
let keyCode = event.keyCode;
let charCode = event.charCode;
if(which == 8 || keyCode == 8 || charCode == 8) {
event.preventDefault();
}
}
But, I can't seem to assign a new event. I've been working with something along these lines, but I have a feeling I'm way off:
document.querySelector('#blank-page').onkeydown = checkKey;
function checkKey(event) {
let which = event.which;
let keyCode = event.keyCode;
let charCode = event.charCode;
if(which == 8 || keyCode == 8 || charCode == 8) {
which == 37;
keyCode == 37;
charCode == 37;
}
}
Does createEvent() possibly come into play here?
I don't know if this will be everything you need but you can use dispatchEvent on the element you want to trigger the event.
You could use it as follows:
JavaScript
window.onload = function(){
document.querySelector('#my-input').onkeydown = checkKey;
}
function checkKey(event) {
console.log(event);
let which = event.which;
let keyCode = event.keyCode;
let charCode = event.charCode;
if(which == 8 || keyCode == 8 || charCode == 8) {
console.log(event.target);
//dispatch a keydown event on the input element where the Backspace key was pressed.
event.target.dispatchEvent(new KeyboardEvent('keydown', {'keyCode': 37, 'key': 'ArrowLeft', 'code': 'ArrowLeft'}));
}else if(keyCode == 37){
//Added this if statement to check that the ArrowLeft keydown event was dispatched.
console.log(event);
}
}
HTML
<input type="text" value="" id="my-input" name="my-input">
Related
I am showing a text area in a modal when I pressed tab it moves to the next input I wrote code to stop this but I didn't work for me.(when I pressed tab the execution even not coming to the acceptTabsSpace function)
$(document).on("keyup", "#collection-text-input", acceptTabsSpace);
function acceptTabsSpace(e){
var keyCode = e.keyCode || e.which;
if (keyCode == 9) {
e.preventDefault();
return false;
}
}
Add the listener to trigger on keydown instead:
$(document).on("keydown", "#collection-text-input", acceptTabsSpace);
function acceptTabsSpace(e){
var keyCode = e.keyCode || e.which;
if (keyCode === 9) {
e.preventDefault();
return false;
}
}
Use keydown instead key up and for tabspaces press tab twice.
$(document).on("keydown", "#collection-text-input", acceptTabsSpace);
function acceptTabsSpace(e) {
var keyCode = e.keyCode || e.which;
if (e.keyCode === 9) {
e.preventDefault();
this.value = this.value.substring(0, this.selectionStart) + "\t" +
this.value.substring(this.selectionEnd);
this.selectionEnd = s + 1;
}
}
I need to perform some action only if the left ALT key was pressed with the letter s.
I can find whether some Alt+s pressed using the keydown event, when oEvent.altKey === true and String.fromCharCode(oEvent.keyCode) === 'S'.
I can also find whether the left or right ALT was pressed by:
oEvent.originalEvent.location === KeyboardEvent.DOM_KEY_LOCATION_LEFT
or
oEvent.originalEvent.location === KeyboardEvent.DOM_KEY_LOCATION_RIGHT
But what I could not find is the way to combine the two.
For make this you have to register two events, keyUp and keyDown and using a single variable can do the trick,
isleftAltPressed : false,
keyUp: function(e)
{
var keyCode = e.which ? e.which : e.keyCode;
if(keyCode == 18)
isleftAltPressed = false;
},
keyDown: function(e)
{
var keyCode = e.which ? e.which : e.keyCode;
if(keyCode == 18 && e.originalEvent.location === KeyboardEvent.DOM_KEY_LOCATION_LEFT)
isleftAltPressed = true;
if(e.altKey && isleftAltPressed && keyCode == 83)
alert("hi");
},
I am working on an old application to make it compatible with firefox. As the old application does not uses Jquery I have to do all my stuffs using Javascript only.
I have a input field for entering date.This field should only allow 0-9 numeric values. So I have modified the code like this for making it compatible with firefox.
var event = window.event || ffEvent ; //ffEvent is the function argument
var intKeyCode = event.keyCode || event.which;
if (intKeyCode < 48 || intKeyCode > 57){
if(event.preventDefault){
event.preventDefault();
}
else{
event.returnValue = false;
}
}
But now the problem is event.returnValue = false allows keys like Backspace,Tab,Delete,Arrow buttons where as event.preventDefault() does not allow these buttons. One must allow these buttons for a input field.
So is there any solutions for firefox which exactly behave same as event.returnValue=false
why not use the keyCodes to check if the character is digit or not
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
var event = window.event || ffEvent ; //ffEvent is the function argument
var intKeyCode = event.keyCode || event.which;
if (intKeyCode > 31 && (intKeyCode < 48 || intKeyCode > 57))
return false;
return true;
}
in the keypress of input field call this event, as
onkeypress="return isNumberKey(event)
All you need to do is skip the event.preventDefault() when the key is one of the keys you want to allow:
window.onload = function () {
document.getElementById('myField').onkeypress = function (event) {
var keyCode = event.keyCode || event.which,
allowedKey = keyCode === 8 || // backspace
keyCode === 9 || // tab
keyCode === 13 || // enter
keyCode === 37 || // left
keyCode === 39 || // right
keyCode === 46 || // del
(keyCode >= 48 && keyCode <= 57);
if (!allowedKey) {
event.preventDefault();
}
};
};
<input type="text" id="myField" />
In my chat application there are some text fields which gets the user login details.
when filling the user details,If user suddenly pressed the ESC key,the data will be lost.
I need to disable the function of ESC key ? which event I need to use ? how can I do that.
my Java Script code is ,
function esc(e){
e = e || window.event || {};
var charCode = e.charCode || e.keyCode || e.which;
if(charCode == 27){
return false;
}
}
Searched a lot in Stack overflow and google.Nothing worked.Please any one help me to do that . Thanks..
You can bind an eventlistener to your input field to catch the Event when Esc is pressed and supress it.
document.querySelector("input").addEventListener("keydown",function(e){
var charCode = e.charCode || e.keyCode || e.which;
if (charCode == 27){
alert("Escape is not allowed!");
return false;
}
});
Example
I got the solution to control the " F5 , Esc , BackSpace(BS) " keys with the following code.
My Java Script code will be ,
document.attachEvent("onkeydown", win_onkeydown_handler);
function win_onkeydown_handler() {
switch (event.keyCode) {
case 116 : // 'F5'
event.returnValue = false;
event.keyCode = 0;
break;
case 27: // 'Esc'
event.returnValue = false;
event.keyCode = 0;
break;
case 08: // 'BackSpace'
if (event.srcElement.tagName == "INPUT"
|| event.srcElement.tagName == "TEXTAREA") {
} else {
event.returnValue = false;
event.keyCode = 0;
}
break;
}
}
Thanks who are all supported me to do this and for your suggestions.
I have used this for a login popup code:
jQuery(document).keyup(function(e){
if(e.keyCode==27 && popupStatus==1){
// alert('not allowed !!!');
// or any other code
return false;
}
});
I have done something similar using jquery to limit entry to numbers
$(inputBox).keydown(function(event) {
// Allow only backspace and delete
var allowed_keys = [
46, // delete
8, // backspace
];
if ($.inArray(event.keyCode, allowed_keys) != -1) {
// let it happen, don't do anything
}
else {
// Ensure that it is a number and stop the keypress
if (event.keyCode < 48 || event.keyCode > 57 ) {
event.preventDefault();
}
}
});
Anyone know how can I disable backspace and delete key with Javascript in IE? This is my code below, but seems it's not work for IE but fine for Mozilla.
onkeydown="return isNumberKey(event,this)"
function isNumberKey(evt, obj)
{
var charCode = (evt.which) ? evt.which : evt.keyCode
if (charCode == 8 || charCode == 46) return false;
return true;
}
This event handler works in all the major browsers.
function onkeyup(e) {
var code;
if (!e) var e = window.event; // some browsers don't pass e, so get it from the window
if (e.keyCode) code = e.keyCode; // some browsers use e.keyCode
else if (e.which) code = e.which; // others use e.which
if (code == 8 || code == 46)
return false;
}
You can attach the event to this function like:
<input onkeyup="return onkeyup()" />
update based on #JoeCoders comment and the 'outdatedness' of my answer, I revised it.
document.querySelector([text input element]).onkeydown = checkKey;
function checkKey(e) {
e = e || event;
return !([8, 46].indexOf(e.which || e.keyCode || e.charCode) > -1);
}
See also this jsFiddle
This code cancels backspace action.
window.onkeydown = function (event) {
if (event.which == 8) {
event.preventDefault(); // turn off browser transition to the previous page
// put here code you need
};
};
$(document).keydown(function(e) {
if (e.keyCode === 8) {
var element = e.target.nodeName.toLowerCase();
if ((element != 'input' && element != 'textarea') || $(e.target).attr("readonly")) {
return false;
}
}
});