Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

218
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!