0

I am trying to prevent default on press F1 so it doesn't open a new tab to support.google.com, instead I want to use it as a hotkey for my app, this is working everywhere, except when I focus a select element for some reason. I put an example:

<!DOCTYPE html>
<html lang="en">

<body>
    <input type="text">

    <select onkeydown="" name="" id="">
        <option value="a">a</option>
    </select>
</body>

</html>

<script>
    window.addEventListener('keydown', (e) => {
        e.preventDefault()
    })
    document.getElementsByTagName('select')[0].addEventListener('keydown', (e) => {
        e.preventDefault()
    })
    document.getElementsByTagName('option')[0].addEventListener('keydown', (e) => {
        e.preventDefault()
    })
</script>

Here if you press F1, it wont do anything, if you focus on the input and press F1 won't do anythin also, but if you open the select dropdown and press F1 then is going to open the help tab. Thats the problem. Any idea how to fix this?

EDIT: So it seems to be a windows/chrome bug, in mozilla this same code works as expected. The prevent event in select and option are not necesary but I put them just in case.

imvenx
  • 194
  • 3
  • 10

1 Answers1

2

You have to attach the event handler on the document rather than window or a particular element:

document.addEventListener("keydown", function(e) {
  if (e.key === "F1") {
    e.preventDefault();
    console.log("F1 Pressed!");
  };
}, false);
<select name="" id="">
  <option value="a">a</option>
</select>

Also your code overrides the onkeydown on the <select> tag. Kindly remove that too.

In the above preview, irrespective of your focus is on the <select> tag or not, F1 is being controlled by JavaScript.

Preview here:

preview

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252