简体   繁体   中英

Keypress but not when input or textarea is in focus

I'm using the code below :

$(document).keypress(function (e) {
    if (e.which === 68 || e.which === 100) {
        doStuff();
    }
});

What i want is to capture the key 'D' as a shortcut to a function in my page. Problem is , this page has inputs and textarea controls and when i'm'typing on this controls, the 'doStuff()' function is called.

How to avoid it ? I want the key 'D' capture only if the user is not typing anything in editable controls.

Thanks !

Alternatively to e.target , you could test if the current active element is an input or textarea:

$(document).keypress(function (e) {
  var focussedTag = document.activeElement && document.activeElement.nodeName;
  if( focussedTag === 'INPUT' || focussedTag === 'TEXTAREA' ) {
    return;
  }
  if (e.which === 68 || e.which === 100) {
    doStuff();
  }
} );

Fiddle: https://jsfiddle.net/e1qtapo6/

Add another check before executing the 'doStuff' function. Check if the user has any input element in focus, and if true then only execute the statement.

Something like this:

$(document).keypress(function (e) {
    if ( (e.which === 68 || e.which === 100) && (!$(input).is(":focus")) ) {
        doStuff();
    }
});
$(document).on('keypress', ':not(:input)', function (e) {
    if (e.which === 68 || e.which === 100) {
        doStuff();
    }
});

Another one -

  $(document).keypress(function (e) {
    if (e.which === 68 || e.which === 100) {
        var _node = e.target.nodeName;
        if( _node !== "INPUT" && _node !== "TEXTAREA" ){
          doStuff();
        }
    }
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM