How to create custom search bar without JavaScript

kyoshee
2 min readJun 12, 2022

Originally posted on kyoshee.com

Photo by Lucia Macedo on Unsplash

Search bar is one of the most common UI elements in the web. Every search engine has one. Trough search bars we interact with the web. Let’s create one for our website.

Layout

Base

To perform a search inside our website we need to send a GET request with some parameter (usually its q as in “query”). The easiest way to do this with plain HTML is by using <form> element with method="GET” and action attributes alongside with <input> element named q and a <button> with submit type.

Simple markup

Now when user clicks submit button, browser will send a GET request to /search with query q={value}.

Reset functionality and accessibility

To give user ability to clear form inputs (in our case just the search input value) we should add <input type="reset"/>. Now by clicking on <input type="reset"> the value in the <input type="search"> will become null. Since all <input> elements must have accessible <label> element, let’s wrap our <input type="search"/> and <input type="reset"/> in <label>.

Markup with label and reset button

Style

Images

For our search bar to have an outstanding view we will add magnifying glass icon before <input type="search" /> and X icon instead of <input type="reset" /> button.

Magnifier glass icon in <img /> element
X icon in <input type=”reset” /> element

CSS rules

Now let’s do some CSS magic. First, add classes to elements.

Simplified markup with classes

And finally, add some CSS for better visibility and accessibility (check out final Codepen)!

Result

As a result, we now have accessible search bar with reset functionality and some fancy icons working without a single JavaScript line. Final result available on Codepen.

Thanks for reading!

--

--