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
Answers
To disable the left and right arrow keys properly without relying on alerts, you can fix your code by ensuring that both event.preventDefault() and e.stopPropagation() (instead of just e.stop()) are called. This will prevent both the default browser behavior and stop the event from propagating further, effectively blocking the navigation between slides.
the correct way to do this would be something like
theres no need to wait for the document to be ready or anything you can just run it straight away