htmlintermediatemit
Clearable Search Input
A search input with a one-click clear button.
2.8k727527167
About this module
A search input that shows a clear (×) button the moment there is text, and returns focus after clearing.
#input#form#search#clear
Source code
Installation
- 1
Create the files
Create `index.html`, `style.css` and (if listed) `script.js` in the same folder.
- 2
Paste the code
Copy each file's source into its matching file.
- 3
Open in the browser
Open `index.html` in any modern browser.
Usage
- 1
Copy the HTML
Paste the markup where you need it.
<link rel="stylesheet" href="style.css" /> <script src="script.js"></script> <div class="mh-search"> <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg> <input id="s" type="search" placeholder="Search docs..." /> <button id="clear" type="button" class="mh-clear" aria-label="Clear search" hidden>×</button> </div> - 2
Wire up the script
Include `script.js` before the closing body tag.
const input = document.getElementById("s"); const clear = document.getElementById("clear"); input.addEventListener("input", () => { clear.hidden = input.value.length === 0; }); clear.addEventListener("click", () => { input.value = ""; clear.hidden = true; input.focus(); });