As we all know, we are constantly learning new and better ways of doing things and today I learned an improved method for clearing a search box to make it more universal and easy to implement.
Let’s first take a look at what we were using:
Published September 11, 2013 | Categories: Web Development
As we all know, we are constantly learning new and better ways of doing things and today I learned an improved method for clearing a search box to make it more universal and easy to implement.
Let’s first take a look at what we were using:
jQuery(document).ready(function(){
//HANDLES CLEARING THE SEARCHBOX
jQuery("#searchBox").focus(function(){
if(jQuery(this).val() === 'Search'){
jQuery(this).val('');
}
});
jQuery("#searchBox").blur(function(){
if(jQuery(this).val() === ''){
jQuery(this).val('Search');
}
});
});
//Directions for use
//Replace the ID #searchBox with the id of your search input field
//Replace the word 'Search' with the desired default input field text
We typically used this to replace our even older method that involved 2 other JavaScript files… yes this replaced 2 files!! We simply add it to our normal global scripts file (scripts.js), update the ID/Class for the sites search field and call it a day!
For the most part this has worked great… until today! I am currently working on a site that we are making responsive and in order to do that efficiently I am cleaning up as much extra as I can. We want to minimize everything we can to ensure that with this enhancement there are no effects on page load. So I go to add it as I normally would but to be sure I first searched the site for all instances of the ‘clearDefault’ class that the (even older) JavaScript was using. I mainly did this so I knew what to test once I put the new code in place but instead I was in for a pleasant surprise of multiple instances with multiple values to replace! So I had to take a step back and reevaluate our current solution to include other scenarios.
I did have a few variations but this is what I settled on:
jQuery(document).ready(function(){
//HANDLES CLEARING THE SEARCHBOX
jQuery('input:text, textarea').focus(function(){
if(this.value === this.defaultValue){
this.value = '';
}
});
jQuery('input:text, textarea').blur(function(){
if (!this.value.length) {
this.value = this.defaultValue;
}
});
});
The differences are as follows:
Note: This does require jQuery on the page but for the most part all of our sites already have jQuery so we decided to use it where we could.
I am not saying this is the only or absolute best way to handle this but it is the solution that fit our needs. If anyone has any suggestions on how this could be improved or done in a more efficient way please comment below!