LongFace
LongFace

Reputation: 1

Prevent function onkeydown javascript

Hello I'm new to this and I have a script that will fire function on keydown. But I also have an input text field box and if I'm typing in that input field box and press the key to that fires the function. The function fires but I don't want the function to fire if I'm typing in the input field would there be a way to do this?

window.addEventListener("onkeydown", keyDown, true);
window.addEventListener("keydown", keyDown);

function keyDown() {
  var e = window.event;
  switch (e.keyCode) {
    case 72: // Key H
      test();
      break;
  }
}

function test() {
  document.getElementById('Codefield').value = Math.random().toString(36).substring(2, 15);
}
<input id="Codefield" value="" type="text">

<input id="Codefield2" value="Stop test function keydown or keydown if typeing here" type="text">

Upvotes: 0

Views: 176

Answers (3)

Barmar
Barmar

Reputation: 780842

You can check whether the current element is an input element.

function keyDown(e) {
  if (this.tagName == 'INPUT') {
    e.stopPropagation();
    return;
  }
  switch (e.keyCode) {
    case 72: // Key H
      test();
      break;
  }
}

Also, don't use window.event. That's non-standard and won't work in Firefox. The event is the first argument to the event listener.

Upvotes: 1

Jack Bashford
Jack Bashford

Reputation: 44087

Maybe you should use a focus selector (from jQuery):

if($("#Codefield2:focus")) {
    thisInput = true;
}

Then add an if statement at the start of your function, and check if thisInput is true or not.

Upvotes: 0

Charlie
Charlie

Reputation: 23778

If you add event listeners to window, all your inputs will fire the function. Add the event listener only where you need it.

document.getElementById('Codefield').addEventListener("onkeydown", keyDown, true);

Another technique would be to check the e.target from inside the trigger function and ignore the code if it is from an input you don't want to handle.

Upvotes: 2

Related Questions