How do you detect the clearing of a "search" HTML5 input?
Detect a cleared search input by checking for an empty value
on the input
event:
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:
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:
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:
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:
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:
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:
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:
Avoid becoming a one-browser wonder
ES6: JavaScript Midas touch
Let's give our code an ES6 facelift:
A multi-browser victory lap
Ensure your code is a good global citizen and plays nice with all browsers:
Was this article helpful?