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

Simplifying Search Activation: A Quick Guide with JavaScript

Posted by Vikash Patel on Saturday, Apr 1, 2023 (Updated Sunday, Jan 7, 2024) Reading time: 2 Min

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:

<form>
  <input type="text" id="search-input" placeholder="$ grep...">
</form>

<!-- If you have a button to activate the 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. JavaScript Functionality:

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

// app.js (app.min.js)
function handleSearchActivation(event, searchInput, searchButton) {
    let KEY_TO_ACTIVATE_SEARCH = '/';
    if (event.key === KEY_TO_ACTIVATE_SEARCH) {
        searchInput.focus();
        searchInput.value = "";
        searchButton.click();
        console.log("Pressed '/' to activate search.");
    }
}

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

    document.addEventListener("keyup", (event) => {
        handleSearchActivation(event, searchInput, searchButton);
    });
};

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.

<head>
  ...
  <script defer src="/js/app.min.js" type="text/javascript"></script>
  ...
</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!



comments powered by Disqus