Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prevent keyup when input focus

I intent to trigger something with spacebar key, but spacebar should be prevent trigger when input is focus.

I'm trying with this way, but it doesnt work well is there any suggestion how to do it right.

$(document).ready(function(){
  $('input').on('blur', function(){
    $(document).on('keyup', function(e){
      if(e.keyCode == 32){
        alert("pressed!");
      }
    });
  }); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <label> Name</label>
  <input type="text" />
  <br />
  <label>Pass</label>
  <input type="text" />
</form>
like image 416
rnDesto Avatar asked Sep 24 '26 08:09

rnDesto


1 Answers

Detach the handler with .off() while input has focus:

$(function(){
    $(document).on('keyup', function(e) {
        if(e.keyCode == 32){
            alert("pressed!");
        }
    });
    $('input').on('focus', function() {
        $(document).off('keyup');
    });
    $('input').on('blur', function() {
        $(document).on('keyup', function(e) {
            if(e.keyCode == 32){
                alert("pressed!");
            }
        });
    });
   
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <label> Name</label>
  <input type="text" />
  <br />
  <label>Pass</label>
  <input type="text" />
</form>
like image 59
Sami Avatar answered Sep 25 '26 23:09

Sami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!