Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Problem

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

Thanks in advance~

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading