Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

220
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda