Reputation: 2479
I would like to catch a pressed key in a div (using tabindex) but not when an input text inside the div is focused. I tried using .not() of jquery, but it doesn't work actually:
$('#content').not('input[type=text]').keydown( function(e) {
console.log(e.which);
});
Here the example. https://jsfiddle.net/kz6es4h0/
Upvotes: 1
Views: 156
Reputation: 749
I would put an if statement in the event listener callback to check if the input has focus at the moment
$('#content').keydown( function(e) {
var hasFocus = $("input").is(":focus");
if (!hasFocus){
console.log(e.which);
}
});
Upvotes: 0
Reputation: 337610
You can check the event.target
to see if it was the input
element that raised it, and stop the processing if so. Try this:
$('#content').keydown(function (e) {
if (e.target.tagName == 'INPUT')
return;
console.log(e.which);
});
Alternatively, you can attach a separate event handler to the input
to stop the event propagation on the keydown
event:
$('input[type="text"]').keydown(function(e) {
e.stopPropagation();
});
Upvotes: 1