-3

I have a textbox

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

with the following JavaScript:

document.addEventListener('keydown', function(event) {
  alert('Key Pressed');
});

Would it be possible to trigger the alert only when the input is not selected?

sebastiandoe5
  • 68
  • 2
  • 8

2 Answers2

1

You can check for event target and then trigger the command.

document.addEventListener('keydown', function(event) {
    if (!event === document.querySelector("#textInput")) {
        alert('Key Pressed');
    }
});

Hope This Helps !

Roope
  • 4,469
  • 2
  • 27
  • 51
damnitrahul
  • 150
  • 1
  • 6
0

Yes it is possible, check document.activeElement to see which element has focus:

document.addEventListener('keydown', function(event) {
  if (document.activeElement && document.activeElement.id !== 'textInput'){
    alert('Key Pressed');
  }
});
John Doherty
  • 3,669
  • 36
  • 38