stack account
stack account

Reputation: 1

Keycode returns undefined and which returns 0

I am working on keypress events.I am using Safari browser and looking for a functioanlity which works on any browser. But the e.keyCode always return undefined and e.which always returns 0. Please find code beloe:

$("a,input,button,select,textarea").live('blur',
    function(e) {
        e.preventDefault();
        var key= e.keyCode || e.which;
        console.log(key);
});

Could any one suggest whats wrong in this code? I want get key code for keypress events.Any help is appreciated.

Upvotes: 0

Views: 4665

Answers (2)

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33933

You wish to detect if an input lost focus dues to a key...

The thing is that the blur event is not related to keys at all. That an event that occurs when an input loses focus.

Even if the "cause" of the focus lost looks to be a "tab", it isn't for the event point of view.

On key hit, several events occur:

  1. keydown
  2. keypress
  3. keyup

The blur then occurs, if the key is a "tab", because the browser does that for you. It not the direct effect from the key.

So the blur occurs after and doesn't carry the key .which information.

Now to detect if an input has lost focus due to a key, you have to "wait a little" and test if the input where there was a key event still is in focus.

To disable a particular key (and its effect), the keydown event is prefered, since the key has not been "printed" yet. It's time to return false.

$("input,textarea").on('keydown', function(e) {
  //e.preventDefault();
  var that = $(this);
  var key = e.which;
  console.clear();
  console.log(key);
  
  setTimeout(function(){
    if(that.is(":focus")){
      console.log("Input still in focus.");
    }else{
      console.log("Input lost focus.");
    }
  },10);
  
  // To disable a key
  if(key==70){  // key "f"
    console.log("That funny letter is forbidden");
    return false
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Try keyboard arrows, tab.<br>
The letter "f" is disabled... For fun.<br>
<br>
<input type="text" placeholder="Type something!"><br>
<br>
<textarea placeholder="Type something!"></textarea>

Upvotes: 1

Julius Dzidzevičius
Julius Dzidzevičius

Reputation: 11000

You bind selectors to the wrong event - you should use something like keypress to catch keypress events

$("a,input,button,select,textarea").live('blur keypress'
  function(e) {
    if (e.type == 'keypress') {
      e.preventDefault();
      var key= e.keyCode;
      console.log(key);
    }
    if (e.type == 'blur') {
      e.preventDefault();
      // do smthg
    }
  }
});

Upvotes: 2

Related Questions