snippets javascript
This post is part of a learning series: Quick Snippets

Activate search with JavaScript

Posted by Vikash on Saturday, Apr 1, 2023 Reading time: 2 Min

The following code snippet will activate the input field by pressing a key on your keyboard. The key binding can we modified based on your requirement.

1. Markup - Search Input Field

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<form>
  <input type="text" id="search-input" placeholder="$ grep...">
</form>

<!-- If you have a button to activate search field like in this website -->
<li class="search-icon">
  <a href="javascript:void(0)" id="search-button">
    <i class="fa fa-search"></i>
  </a>
</li>

2. Functionality - JavaScript code

In this website the search can be activated by pressing / key on your keyboard.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
// app.js (app.min.js)
function handle_search_activation(event, searchInput, search_button) {
    let KEY_TO_ACTIVATE_SEARCH = 's' ;
    if (event.key === KEY_TO_ACTIVATE_SEARCH) {
        searchInput.focus();
        searchInput.innerHTML = "";
        search_button.click();
        console.log("Pressed s to activate search.");
    }
    return;
}

window.onload = function () {
    console.log("Document loaded...");
    let searchInput = document.querySelector("#search-input");
    let search_button = document.querySelector("#search-button");

    document.addEventListener("keyup", (event) => {
        handle_search_activation(event, searchInput, search_button);
    });
};

Add the file in head or footer. You can also copy-paste the code in an existing js file to reduce the number of files requested.

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

Also, customize the UI according to your liking.

That’s it. you now you can press a key to activate the search input and start typing. You also add a submit button and press enter to search.

Thanks.