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

219
Visualizações
Prevent tab key from selecting URL in Javascript/Jquery

I'm making a game, and there's a leaderboard. I want the user to be able to toggle the leaderboard by hitting the TAB key. Here is my code:

keysPressed = {};

if(keysPressed[KEY_TAB]){
    if(leaderboard.style.display == 'none'){
        $(leaderboard).fadeIn(100);
    } else {
        $(leaderboard).fadeOut(100);
    }

    keysPressed[KEY_TAB] = false;
}

document.addEventListener('keydown', (event) => {
    keysPressed[event.key.toLowerCase()] = true;
}, false);

document.addEventListener('keyup', (event) => {
    keysPressed[event.key.toLowerCase()] = false;
}, false);

Note: leaderboard is just document.getElementById('leaderboard')

This all works fine, but whenever I hit the tab key, the webpage (I'm using Chrome) automatically selects/deselects the URL bar. Is there a way I can prevent the TAB key from doing this, or do I need to switch to a different key? Here is an screenshot demonstrating my problem:

Problem

JavaScript is prefered, since I am rather new to jQuery, but I am willing to go either.

Thanks in advance~

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Use Event.preventDefault()

From MDN :

The preventDefault() method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.

The event continues to propagate as usual, unless one of its event listeners calls stopPropagation() or stopImmediatePropagation(), either of which terminates propagation at once.

As noted below, calling preventDefault() for a non-cancelable event, such as one dispatched via EventTarget.dispatchEvent(), without specifying cancelable: true has no effect.

document.addEventListener('keydown', (event) => {
    if (event.key == "Tab") {
        event.preventDefault();
    }
}, false);

about 4 years ago · Santiago Trujillo 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