Pregunta

I have a

$(document).keyup(function(e) {
  //some code is here
});

code, that works as expected: it fires when I press any key on the keyboard. I want it to fire, but not when the cursor is in the

<input type="text" id="excludeMeFromFiring">

which is on the page.

How to modify the code above to exclude firing when typing in the input text field with a special id? So it doesn't fire if the cursor is in the input text field.

Thank you.

¿Fue útil?

Solución

It's easy to do that in the keyup function:

$(document).keyup(function(e) {
    if ($(e.target).closest("#excludeMeFromFiring")[0]) {
        return;
    }

    // It's not that element, handle it
});

That's the general case; because input elements can't have any elements within them, you could just use e.target.id rather than closest:

$(document).keyup(function(e) {
    if (e.target.id === "excludeMeFromFiring") {
        return;
    }

    // It's not that element, handle it
});

I use closest whenever the element can have other elements inside it.

Otros consejos

Try

$(document).keyup(function (e) {
    if(e.target.id === 'excludeMeFromFiring'){
        console.log('no');
    }else{
        console.log('hi');
    }
});

$(document).keyup(function (e) {
    if(e.target.id !== 'excludeMeFromFiring'){
       console.log('hi');
    }
});

Another Example:

$('#excludeMeFromFiring').keyup(function(e) {
    e.stopPropagation();
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top