ben_aaron
ben_aaron

Reputation: 1522

Unbinding custom key event for text input with JQuery

I'm binding a function to the keydown event when the ENTER key is pressed. I want this function to fire on the ENTER keydown unless the user types in the textarea with the id input_area:

$(document).keydown(function(e) {
  if (e.keyCode == 32 && e.target != $("#input_area")) {
  scroll_to_location();
  }
});

I tried to unbind the whole keydown with $(document).unbind('keydown') but this does exactly that for the whole document and not just for the brief period when there is text input.

Is there a neat way of unbinding the event for the textarea input using JQuery?

Upvotes: 0

Views: 32

Answers (2)

Taplar
Taplar

Reputation: 24965

You could check the originalEvent target id to see if it is the element that should be ignored.

$(document).on('keydown', function (e) {
    if (e.originalEvent.target.id === 'input_area') return;

    //do logic
});

Upvotes: 1

Tom G
Tom G

Reputation: 3650

I would recommend doing the bind/ unbind with on and off like this:

$(document).on('keydown', '#input_area', function(e) {
   if(e.which == 13) {
      console.log("enterPressed");
   }
});

$(document).on('click', '#unbindBtn', function(e) {
   $(document).off('keydown', '#input_area');
});
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  </head>
  <body>
    <input id="input_area" placeholder="Tap Enter" />
    <button id="unbindBtn">Unbind</button>
  </body>
</html>

Upvotes: 1

Related Questions