Reputation: 161
I am trying to disable arrow up and down function for a selection list field. I have searched and tried all the options but could not disable. When alerting with the keys it is working but when I try to disable it does not work. Is there any updates related with browsers
My Chrome Version: 89.0.4389.128 (Official Build) (64-bit)
// we are closing the arrow keys for selection
$(function()
{
$('.form-contact').on('keyup',function(e) {
if(e.keyCode === 38 || e.keyCode === 40) { //up or down
// alert(e.keyCode)
e.preventDefault();
return false;
}
});
});
Last code something like this. it does not prevent arrow up or down to the list but it prevents selection by enter from the list. So better than nothing. Still open my question.
$('.form-contact,.form-company,.form-address,.form-postcode,.form-phone,.form-email').on('keydown', (e) => {
if (e.target.localName != 'input') { // if you need to filter <input> elements
switch (e.keyCode) {
case 38: // up
case 40: // down
e.preventDefault();
break;
default:
break;
}
}
}, {
capture: true, // this disables arrow key scrolling in modern Chrome
passive: false // this is optional, my code works without it
});
Upvotes: 1
Views: 3476
Reputation: 332
Instead of keyup, use keydown event
$(function()
{
$('.form-contact').on('keydown',function(e) {
if(e.keyCode === 38 || e.keyCode === 40) { //up or down
// alert(e.keyCode)
e.preventDefault();
return false;
}
});
});
Upvotes: 1
Reputation: 1080
This might be helpful:
window.addEventListener("keydown", function(e) {
if(["Space","ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].indexOf(e.code) > -1) {
e.preventDefault();
}
}, false);
Found it here Disable arrow key scrolling in users browser
Upvotes: 0