Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ghost text - how to have faint text in textbox

I've an online form:

http://yoursdproperty.com/index.php?option=com_chronocontact&Itemid=56

I would like to have some faint gray text there so that when the user clicks on it, it disappears

exactly like in this StackOverflow form where in the title of the question it says "what's your programming question, be descriptive?"

what is the simplest way to implement this?

like image 253
Alex Gordon Avatar asked Jan 31 '10 23:01

Alex Gordon


3 Answers

In HTML5, this is achieved very easily via the placeholder attribute - not sure how widely supported that is right now, though.

like image 71
Michael Borgwardt Avatar answered Nov 08 '22 11:11

Michael Borgwardt


You made no mention of jQuery, or any other javascript framework, so I'm going to give you the pure Javascript solution.

Some boolean logic based upon the value of the box to set the font color. When the user clicks the input, if the value is equal to your default value, you erase the contents. If it's not, you do nothing. When the user leaves the box, if the values are empty, add your default text in again.

// Reference our element
var txtContent  = document.getElementById("content");
// Set our default text
var defaultText = "Please enter a value.";

// Set default state of input
txtContent.value = defaultText;
txtContent.style.color = "#CCC";

// Apply onfocus logic
txtContent.onfocus = function() {
  // If the current value is our default value
  if (this.value == defaultText) {
    // clear it and set the text color to black
    this.value = "";
    this.style.color = "#000";
  }
}

// Apply onblur logic
txtContent.onblur = function() {
  // If the current value is empty
  if (this.value == "") {
    // set it to our default value and lighten the color
    this.value = defaultText;
    this.style.color = "#CCC";
  }
}
like image 41
Sampson Avatar answered Nov 08 '22 11:11

Sampson


You can use this jQuery plugin.

like image 4
SLaks Avatar answered Nov 08 '22 11:11

SLaks