yensdesign - Tutorials, Web Design and Coding

Daily free tutorials about web design, coding, jquery and more

Posts Tagged ‘hide’

Fast Tip: Show or hide text in a search box with focus / blur

Thursday, December 18th, 2008

Currently the search boxes are in the most of websites because the content is growing continually and it’s useful find out something with a simple search. In order to provide them more interaction I want to show you a simple but very useful javascript code snippet to show or hide the default contained text in a search box managing the events focus and blur.

So if we have this html input text box:


<input onClick="" id="txtSearch" type="textbox" value="Search the web..." />

The javascript code that you must put before closing the body element would be:


<!-- Put it at the end before closing body element! -->
<script type="text/javascript">
	document.getElementById("txtSearch").onfocus = function(){
		if(this.value == "Search the web...") this.value = "";
	};
	document.getElementById("txtSearch").onblur = function(){
		if(this.value == "") this.value = "Search the web...";
	};
</script>
<!-- Put it at the end before closing body element! -->

The jQuery code would be as follows:


$(document).ready(function(){
	$("#txtSearch").blur(function(){
		if(!$(this).val()) $(this).val("Search the web...");
	});
	$("#txtSearch").focus(function(){
		if($(this).val() == "Search the web...") $(this).val("");
	});
});

And that’s all guys, I hope you can use it for your search boxes and thanks for visiting us! We had a huge quantity unique visitors yesterday and it seems that today will be better :D