rnDesto
rnDesto

Reputation: 259

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>

Upvotes: 3

Views: 3163

Answers (1)

Sami
Sami

Reputation: 2110

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>

Upvotes: 4

Related Questions