Giacomo Cerquone
Giacomo Cerquone

Reputation: 2479

How to exclude an area for keydown?

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

Answers (2)

Jonathon Blok
Jonathon Blok

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

Rory McCrossan
Rory McCrossan

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);
});

Example fiddle

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();
});

Example fiddle

Upvotes: 1

Related Questions