Halo
Halo

Reputation: 1970

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~

Upvotes: 1

Views: 256

Answers (1)

Hyyan Abo Fakher
Hyyan Abo Fakher

Reputation: 3537

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);

Upvotes: 2

Related Questions