When designing or developing a website, having a feature that automatically clears default text in a text box on input can significantly improve usability. This article explains how to implement this feature using CSS, JavaScript, and HTML.
Setting Default Text Style with CSS
First, set the default style for the text box. Specifically, set the text color of text boxes with the class name .clText to gray (#999999). This color can be changed to your preference.
<style type="text/css">
<!--
body{
margin:0;
padding:0;
}
h1{
font-size:16px;
font-weight:normal;
line-height:2.0em;
text-align:center;
padding:15px 0;
}
#idWrap{
width:600px;
margin:0 auto;
text-align:center;
}
#idText{
text-align:center;
}
.clText{
color:#999999;
}
-->
</style>
Controlling Text Box Behavior with JavaScript
Next, use jQuery to control the behavior of the text box. The following script defines the actions for when the text box gains and loses focus.
First, load the jQuery library.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
Then, write the script to control the text box behavior. When the text box (with class .clText) gains focus, its value is cleared, and the text color is set to black (#000000). When it loses focus and the value is empty, the value is set to “Enter text” and the text color is changed to gray (#999999).
<script type="text/javascript">
$(function(){
$(".clText").focus(function(){
if(this.value == "Enter text"){
$(this).val("").css("color","#000000");
}
});
$(".clText").blur(function(){
if(this.value == ""){
$(this).val("Enter text").css("color","#999999");
}
});
});
</script>
Placing the Text Box with HTML
Place the text box with the following HTML code.
<div id="idWrap">
<h1>When you input text in the box below, the default text will be cleared (hidden).</h1>
<div id="idText">
<input type="text" class="clText" value="Enter text" />
</div>
</div><!--/idWrap-->
Demo Page for Automatically Clearing Default Text in a Text Box
You can check the actual operation on the demo page below.
Demo Page for Automatically Clearing Default Text in a Text Box
Summary
In this article, we explained how to automatically clear the default text in a text box on input using CSS, JavaScript, and HTML. This simple implementation can greatly improve usability and can be applied to various websites and applications.
Note: Use this at your own risk. Do not reuse the Google Analytics tag within the demo page.