DEV Community

Cover image for How to make the search bar focus using JavaScript
arize
arize

Posted on

How to make the search bar focus using JavaScript

This is the process I took to create a similar search bar focus feature just like the one Google uses in Google and YouTube search bar and some other products.
This feature allows you to enter the search bar from anywhere on the screen just by hitting the forward-slash (/) button on your keyboard, you wouldn't need to scroll to the search bar and start clicking with your mouse to start searching.

This is how I did it;
I started by creating a simple HTML page adding a search bar tag and giving it an ID.

`<!DOCTYPE html>



Search Bar Focus


`

Yes, to make the code cleaner I put the JavaScript in a separate file.

`document.addEventListener('keydown', function(event) {
// Check if the key pressed is the one you want to trigger the focus
if (event.key === '/') { // Change '/' to the key you want to use
var searchInput = document.getElementById('searchInput');

// Select the text in the input field
searchInput.setSelectionRange(0, searchInput.value.length);

// Focus on the search input
searchInput.focus();

// Prevent the default action of the '/' key
event.preventDefault();

}
});`

I added comments to some places in the code just in case.

Image description
The result should look like this.
This is just basic HTML and JavaScript. This is the GitHub link in case you want to fork the repo or copy the codes and use them in your project.

It would be really exciting to have someone add a search icon and probably a mic icon on the right too, and adjust the position of the search bar.

https://github.com/arize99/search-bar-focus again in case you missed the repo. I hope to see what amazing projects you guys add this feature to.

Top comments (0)