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);
});
};
3. Link the Script File in Your HTML:
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!
-
Previous
Setting Up a PostgreSQL Container: A Quick Guide -
Next
AWS - Host Static Website With S3 + Cloudfront + Route53