Explain Codes LogoExplain Codes Logo

How do you detect the clearing of a "search" HTML5 input?

javascript
input-event
debouncing
autocomplete
Anton ShumikhinbyAnton Shumikhin·Jan 8, 2025
TLDR

Detect a cleared search input by checking for an empty value on the input event:

document.querySelector('input[type="search"]').addEventListener('input', (e) => { // Goodbye search input, hope to see you soon! if (!e.target.value) console.log('Cleared!'); });

This event listener watches your search input for any changes. As soon as it turns blank, this script jumps into action.

Seize the 'input' event and make it work for you

To be aware of real-time user actions, hitch a ride on the built-in input event:

let searchInput = document.querySelector('input[type=search]'); searchInput.addEventListener('input', (e) => { // This event gets lost in the Bermuda Triangle when cleared if (!e.target.value) console.log('Cleared!'); });

Battle of the Browsers

The search event, when called upon, might act like a moody teenager across browsers. In Chrome, it's all hands on deck when the clear button is clicked, but Firefox and Safari may sulk. So let's hold an intervention:

inputElement.addEventListener('search', function(evt) { if (evt.target.value === '') { // I hereby declare you cleared, Mr. Search Input console.log('Search cleared via clear button'); } });

Debouncing: Calming the Hyperactive Input Event

Real-time search can resemble a caffeine-addict on steroids. Let's put our parental shoes on and introduce some discipline with a technique called debouncing:

let debounceTimeout; const debounce = (fn, delay) => { return function() { clearTimeout(debounceTimeout); // Patience is a virtue, let's put the coffee down debounceTimeout = setTimeout(() => fn.apply(this, arguments), delay); }; }; const handleInput = debounce(() => console.log('Input changed'), 250); document.querySelector('input[type=search]').addEventListener('input', handleInput);

Caveats because life is a box of chocolates

There are elements to fine-tune when peppering your UI with JavaScript.

Autocomplete and Form Reset

Autocomplete or form reset can be your secret admirer or your worst nightmare, depending on your implementation. Here's how to harness them:

form.addEventListener('reset', function() { // Reset button can be a party-pooper, so you need to handle that console.log('Form reset - search input cleared'); });

Clear as mud: Detecting the 'X' button

If everything else fails, you can add an invisible cape in the form of a transparent button over your clear 'X' button and lurk until it's clicked:

<input type="search" id="searchInput"/> <div onclick="detectClear()" style="position: absolute; right: 2px; top: 2px;"></div>

Make sure it doesn't look like your button borrowed the Invisibility Cloak from Harry Potter.

Readable code: courtesy or necessity?

Being a coding hero doesn't just involve being able to tame complex logic or trap bugs. Writing code, which in three months you won't dismiss as having been written by a dictionary-illiterate uncle, is also a virtue:

function onSearchCleared() { // Does this make you YELL with joy? console.log('Search input cleared!'); } document.getElementById('searchInput') .addEventListener('input', (e) => { // It was great while it lasted if (!e.target.value) onSearchCleared(); });

User Experience: Don't make me think!

Here's proactive customer service in action. Tear down those "Help" hotlines- update the UI when a search input is cleared:

let inputElement = document.querySelector('input[type="search"]'); inputElement.addEventListener('input', function(evt) { if (evt.target.value === '') { // "Sorry for your loss," says the empathetic UI updateSearchStatus('Search cleared...'); } });

Avoid becoming a one-browser wonder

ES6: JavaScript Midas touch

Let's give our code an ES6 facelift:

const searchInput = document.querySelector('input[type=search]'); searchInput.addEventListener('input', ({currentTarget}) => { if (!currentTarget.value) console.log('Search input cleared'); });

A multi-browser victory lap

Ensure your code is a good global citizen and plays nice with all browsers:

inputElement.addEventListener('input', function(evt) { const isCleared = evt.target.value === ''; handleSearchInput(isCleared); }); function handleSearchInput(cleared) { if (cleared) { // "I play nicely with all!" says the universal-code console.log('Search input cleared across all browsers'); } }