I’m creating a search field that when you type something in to a clear button appears where when clicked will clear what you’ve been typing. The clear button should go away when you loose focus of the input field however come back if you focus in on the input field and there is something inside it.
The function does not need to be flexible to the sense that the markup structure can vary, the markup structure needs to be . It just needs to accommodate different selectors.
Markup:
<div id="searchfield">
<div id="clearbutton"></div>
<input name="searchbox" type="text" id="searchbox">
</div>
The JavaScript Function: (Note: I’m using jQuery)
function clearableSearchBox(searchbox, clearbutton) {
var searchbox = jQuery(searchbox);
var clearbutton = jQuery(clearbutton);
// When a user starts to enter into the textbox, fade in the clear button
searchbox.keydown(function() {
clearbutton.fadeIn('fast');
});
// When a user clicks the clear button, remove the contents of the searchbox
clearbutton.click(function() {
searchbox.val('');
});
// When the textbox is unfocused, fade out the clear button
searchbox.focusout(function() {
clearbutton.fadeOut('fast');
});
// If there's something in the search box, fade in the close button
searchbox.focusin(function() {
if(searchbox.val()) {
clearbutton.fadeIn('fast');
}
});
}
Finally, when you want to use the function, call it:
clearableSearchBox("#searchbox", "#clearbutton");
Any suggestions on optimization/best practices would be greatly appreciated. Thanks very much!
it would be possibly best practice if you use
$to prefix jquery-variables, eg:otherwise … nope … i’ve spotted nothing to opt …
you could use chaining, eg:
but i’m not a big friend of that … dunno why 🙂