Focusing input box on keydown causes key to be typed into input box

Focusing input box on keydown causes key to be typed into input box

I was writing code for a MediaWiki .js customization file to focus the search box (an input with id searchInput on most skins) when the / (slash) key is pressed.

I noticed that when I typed the slash, the input box focuses, but the slash is also typed into the input box, which I don't want.

Here's a minimal example which seems to have the issue as well:

document.addEventListener("keydown", function (event) {
    if (event.key === '/') {
        const searchInput = document.getElementById("searchInput");
        if (searchInput) {
            searchInput.focus();
        }
    }
});
<input id="searchInput" />

jQuery can be used if needed since it is included with MediaWiki.

Answer

Adding

event.preventDefault();

after your "focus" line should resolve your issue. It also may be necessary to add a return false; line as well (although this is probably only really needed for older browser support, which you may not particularly be concerned about). In reality, the event.preventDefault(); should be sufficient.

document.addEventListener("keydown", function (event) {
    if (event.key === '/') {
        const searchInput = document.getElementById("searchInput");
        if (searchInput) {
            searchInput.focus();
            event.preventDefault();
            return false;
        }
    }
});

Enjoyed this question?

Check out more content on our blog or follow us on social media.

Browse more questions