Simplifying Search Activation: A Quick Guide with JavaScript

Learn how to enhance user experience by activating the search input field with a simple key press on your website. This quick guide provides a code snippet and easy-to-follow steps.

WORDS: 266 | CODE BLOCKS: 3 | EXT. LINKS: 0

Learn how to enhance user experience by activating the search input field with a simple key press on your website. This quick guide provides a code snippet and easy-to-follow steps.

1. HTML Markup for Search Input:

html
 1<form>
 2  <input type="text" id="search-input" placeholder="$ grep...">
 3</form>
 4
 5<!-- If you have a button to activate the search field like in this website -->
 6<li class="search-icon">
 7  <a href="javascript:void(0)" id="search-button">
 8    <i class="fa fa-search"></i>
 9  </a>
10</li>

2. JavaScript Functionality:

Activate the search input field by pressing a key (in this example, the ‘/’ key). Modify the key binding according to your preferences.

javascript
 1// app.js (app.min.js)
 2function handleSearchActivation(event, searchInput, searchButton) {
 3    let KEY_TO_ACTIVATE_SEARCH = '/';
 4    if (event.key === KEY_TO_ACTIVATE_SEARCH) {
 5        searchInput.focus();
 6        searchInput.value = "";
 7        searchButton.click();
 8        console.log("Pressed '/' to activate search.");
 9    }
10}
11
12window.onload = function () {
13    console.log("Document loaded...");
14    let searchInput = document.querySelector("#search-input");
15    let searchButton = document.querySelector("#search-button");
16
17    document.addEventListener("keyup", (event) => {
18        handleSearchActivation(event, searchInput, searchButton);
19    });
20};

Include the JavaScript file in the head or footer of your HTML. Alternatively, copy and paste the code into an existing JS file to reduce file requests.

html
1<head>
2  ...
3  <script defer src="/js/app.min.js" type="text/javascript"></script>
4  ...
5</head>

4. Customize UI:

You can also tailor the UI of the search input to match your preferences.

Now, users can effortlessly activate the search input by pressing a key and start typing. You can also add a submit button and press ‘Enter’ to initiate the search.

Thanks for Simplifying Your User’s Experience!