skip to Main Content

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


  1. 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.

    jQuery(document).ready(function( $ ){  
      document.onkeydown = function(e) {
        if (e.keyCode == 39 || e.keyCode == 37) { // Right arrow (39) and Left arrow (37)
          e.preventDefault();   // Prevent default behavior
          e.stopPropagation();  // Stop event propagation
        }
      };
    });
    
    Login or Signup to reply.
  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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search