Improve mobile search Ux

There’s a good chance you have a search bar on your website and some autocompletion.

The search feature has changed over the past years. There’s no need to reload the page to display the search results anymore, and that’s cool.

However, especially on mobile devices, the experience is not always right.

Sometimes, search results are too far from the search input, and the keyboard stays even if the user has pressed the search icon or the “go-to” button.

It leads to a confusing state, where you don’t know what’s happening.

One possible way to solve this is to use JavaScript to close the keyboard.

I like to do this because it indicates that something is happening when the user presses a button.

In React, you can do that with the following function:

 const handleKeyPress = e => {
    if (e.key === 'Enter') {
      e.target.blur()
    }
  }

Assuming you use a search input that looks like that:

<label htmlFor="searchbar">
    Search
</label>
<input
        id="searchbar"
        type="search"
        autoComplete="off"
        onKeyPress={handleKeyPress}
/>

Just use the blur() method, and the mobile keyboard will close. Of course, you don’t have to use React. It’s available in JavaScript in general.