When you click on the "Ask Question"
button on Stack Overflow, the question title section is prepopulated with light gray text that reads
"what's your programming question? be specific"
Then when you click inside the Title field and start typing, that text disappears.
I want to do the same thing in my app.
Is there a trick in jQuery to accomplish that?
And, specifically, how do you change the text color from light gray for the placeholder text to the default text color when someone starts typing?
The easiest way to achieve this is with html (albeit html5)'s placeholder
attribute:
<input type="text" placeholder="Enter email address." name="email" />
It will appear as "lighter colored" text that disappears when the user starts entering something.
However, if you really want/need to use jQuery (as the above html-solution is only usable in the more modern/compliant browsers), here's a way:
$(document).ready(
function(){
$('input:text').each(
function(){
$(this).click(
function(){
$(this).val('');
});
$(this).blur(
function(){
if ($(this).val == '') {
$(this).val($(this).attr('placeholder'));
}
});
});
});
)
in the final if
, and also to add a slightly revised version of the above that features slightly greyed-out placeholder
text (as I assume the OP would like, given his question in the comments, below):
$(document).ready(
function(){
$('input:text').each(
function(){
$(this)
.val($(this).attr('placeholder'))
.css('color','#999');
$(this).click(
function(){
$(this)
.val('')
.css('color','#000');
});
$(this).blur(
function(){
if ($(this).val() === ''){
$(this)
.val($(this).attr('placeholder'))
.css('color','#999');
}
});
});
});
JS Fiddle demo.
<input type="text" value="whats your programming question" id="txt"/>
$(document).ready(function(){
$('#txt').click(function(){
this.value = '';
this.style.color = 'black';
}).blur(function(){
if ( this.value == '')
this.value = 'whats your programming question';
this.style.color = 'lightgray';
});
});
The solutions presented so far have a drawback: the prompted text is submitted to the server if the user doesn't enter any value in the input. You can find here a better solution that also takes care of this issue: http://kyleschaeffer.com/best-practices/input-prompt-text/
Though I don't know how to do it in jQuery, it's pretty simple to do so directly with JavaScript. Just assign a function that clears the text field on the onClick property of the field, like so:
<input type="text" id="textID" onclick="clear" />
And you Java script would be something like:
function clear()
{
document.getElementById("textID").value = "";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With