I have an event that I want to fire whenever R or SPACE is pressed, with the exception of when in an input field.
Specifically, I'm worried about <input id='nameInput' type='text'>
that I dynamically create when I click in a div and remove onchange
/ onblur
. That's why I tried checking if( !$('#nameInput') )
, but $('#nameInput')
is a jQuery object, so its boolean value is always true
(and hence !$('#nameInput') == false
).
$(window).bind('keyup',
function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 32 || code == 82){
if( !$('#nameInput') ){
roll();
}
}
}
);
I have a solution that utilizes a global boolean variable getting set in onfocus of the input field, but I'd like a solution that doesn't require a global variable if it's possible.
Is there a way to determine what element currently has focus?
You can use document.activeElement
to know wich element currently has focus.
if (!$(document.activeElement).is('input, textarea')) {
roll();
}
You could also make use of the :focus
selector.
if (!$(':focus').is('input, textarea')) {
roll();
}
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.