Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

230
Visualizações
Prevent default on select focused

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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda