Yes, it can be done via JavaScript, but some browsers also support it natively. The placeholder
attribute is an HTML5 addition; certain browsers (such as WebKit-based browsers) support it already.
Example using jQuery 1.4
<!-- this will work automatically for some browsers -->
<input type="text" placeholder="enter some text">
<!-- script for browsers which don't support it natively -->
<script type="text/javascript">
$.fn.placeholder = function(){
// quit if there's support for html5 placeholder
if (this[0] && 'placeholder' in document.createElement('input')) return;
return this
.live('focusin',function(){
if ($(this).val() === $(this).attr('placeholder')) {
$(this).val('');
}
}).live('focusout',function(){
if ($(this).val() === ''){
$(this).val( $(this).attr('placeholder') );
}_
});
}
$('input[placeholder]').placeholder();
</script>
Note: code was copied from this Pastie linked from jQuery 1.4 hawtness. I haven't verified that it works across browsers. You can find other JavaScript solutions on Google if you don't use jQuery.