Skip to content
JavaScript

How to Close the Mobile Keyboard on Return in JavaScript

2 min read

A nice feature that appears on some sites is the ability to have realtime search results. You have a search input that as you type the results update dynamically below without the need tho hit return/enter. However, if to achieve this the form's default behaviour to submit is disabled, on mobile and tablet the onscreen keyboard won't close on return. This can be confusing to the end-user.

To get round this we can listen for the return key being pressed and removing the focus on the input field using the blur event.

const hideMobileKeyboardOnReturn = (keyboardEvent) => {
    element.addEventListener('keyup', (keyboardEvent) => {
        if (keyboardEvent.code === 'Enter') {
            element.blur();
        }
    });
};

document.querySelementectorAll('[type=search]').forEach((element) => {
    hideMobileKeyboardOnReturn(element);
}); 

We're using the KeyboardEvent.code property here to identify the return/enter key. This property represents a physical key on the keyboard. Browser support for this property is fairly good; however, I've found there's still a need to include a fallback for the now deprecated KeyboardEvent.keyCode property to get this working on some mobile browsers.

key.keyCode === 13

To include a fallback we can update the hideMobileKeyboardOnReturn function to the following:

const hideMobileKeyboardOnReturn = (element) => {
    element.addEventListener('keyup', (keyboardEvent) => {
        const key = keyboardEvent.code || keyboardEvent.keyCode;
        if (key === 'Enter' || key === 13) {
            element.blur();
        }
    });
};

Here, if keyboardEvent.code is undefined (e.g. on older browsers), the code will fallback to use the keyboardEvent.keyCode property.

If you're wondering how to determine the values for the code and keyCode properties, I recommend checking out the JavaScript Keycode website.

© 2024 Andy Carter