[Javascript] Search Box to Show Default Text on Load and Cleared When Focused

Posted in Web Development on 9 July 2012 1 comment

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.

Demo Page

Click here to go to the DEMO PAGE

Using Plain Javascript

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.

Using JQuery

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 :)

 

Posted by Zen on 9 July 2012 1 comment
Tags : , ,



or Subscribe to specific category only :




  - 1 Comments


Hi Zen!!!
This is very nice. I am going to implement by using this. Thanks for sharing.

Leave a Reply

You must be logged in to post a comment.

Previous Post
«
Next Post
»