Skip to content
Advertisement

How do I set a keyup event in all the document except in one element?

I have the following piece of code:

$(document).ready(function(){
    $(document).on("keyup",function(e){myFunction(e)});
});

function myFunction(e){
    console.log("hi");
}

I have this input:

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

And I need to call myFunction whenever, except when I’m typing on that input, I mean something like this:

$(document).on("keyup",":not(#inp1)",function(e){myFunction(e)});

How do I do that?

Advertisement

Answer

To do this you can attach the keyup event handler to the document then use a condition to avoid calling myFunction() if the element which raised the event has the id of inp1.

$(document).ready(function() {
  $(document).on("keyup", function(e) {
    e.target.id !== 'inp1' && myFunction(e);
  });
});

function myFunction(e) {
  console.log("hi", new Date().getTime());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="inp1">

Note that the method of identifying the element can be amended as required, I simply used the id here as it was the simplest to demonstrate.

Also note that this method relies on the keyup event bubbling up the DOM. If you have any calls to stopPropagation() on key event handlers on parent elements it may prevent this approach from working.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement