I want to disable left and right arrows key of keyboard on a webpage, preventing the scroll to the previous or next slide.
I’ve this code:
jQuery(document).ready(function( $ ){
document.onkeydown = function(e) {
if (e.keyCode == 39 ) {
alert('Not allowed');
event.preventDefault();
e.stop();
}
if (e.keyCode == 37 ) {
alert('Not Allowed!');
event.preventDefault();
e.stop();
}
};
});
This is working: when I click on arrow key, the site shows alert, and then when I close it, its righty do anything (so I stay on the current slide).
The problem is when I disable the alerts: in this case, when I click on rigt or left key,the site goes to the next or to the previous slide, ignoring the block of the keyboard.
Any suggestion?
Thanks
2
the correct way to do this would be something like
document.addEventListener('keydown',keydown,true);
function keydown(e){
switch(e.key){
case 'ArrowLeft' :
case 'ArrowRight' :
e.stopImmediatePropagation();
e.preventDefault();
}//switch
}//keydown
theres no need to wait for the document to be ready or anything you can just run it straight away
<script>
var $=sel=>document.querySelector(sel);
var adj=(sel,prop,v)=>{
var node=$(sel);
var value=node.style[prop];
value=value||0;
value=parseInt(value)+v;
node.style[prop]=value+'px';
}
document.addEventListener('keydown',keydown,true);
function keydown(e){
if($('#chk').checked==false)return;
switch(e.key){
case 'ArrowLeft' :
case 'ArrowRight' :
e.stopImmediatePropagation();
e.preventDefault();
}//switch
}//keydown
</script>
<style>
body {margin:25px}
#box {position:relative;height:50px;background:lightblue}
#slider {position:absolute;width:50px;height:100%;background:lightgreen;margin:2}
#chk-root {display:flex;align-items:center;margin:10px 0;}
input {width:25px;height:25px;cursor:pointer;margin:0 10px}
label {font-size:20px;cursor:pointer}
</style>
<div>click blue box then arrows to slide</div>
<div id=chk-root>
<label for=chk>enabled</label>
<input id=chk type=checkbox>
</div>
<div id=box tabindex=-1>
<div id=slider></slider>
</div>
<script>
$('#box').onkeydown = e=>{
if(e.key=='ArrowLeft')adj('#slider','left',-5);
if(e.key=='ArrowRight')adj('#slider','left',5);
};
</script>
4