Very often we want our search box to show a default text such as “Search…” when it is loaded. Then when users clicked on the search box, the word is cleared, allowing user to enter their search query. We will see how to do that in this short guide in both plain Javascript and jQuery.
You can use the jQuery method if your website is already using jQuery library. If not, it is not recommended because there is no need to load a library just for this simple script.
Click here to go to the DEMO PAGE
Below shows the codes to achieve the behavior in a simple search form using plain javascript.
It is pretty straightforward, we just need to set the default text, the onfocus & onblur behaviors to the search form’s text <input> element.
But make sure you placed the javascript codes AFTER the search form or else you will get an error complaining that the element doesn’t exist.
Below shows the codes for jQuery, where the jQuery library is loaded from Google API. You can also use your local copy of jquery.js if you want.
Similar codes go for jQuery but with different syntax. Also, for jQuery, you can put the javascript anywhere (it does not matter before or after the form)
Hope this short guide helps. Please Share or Like it if it does :)
Hi Zen!!!
This is very nice. I am going to implement by using this. Thanks for sharing.