HTML5 Placeholder text for your Drupal 7 Search Field

HTML5 has a bunch of new form attributes and one of these can neatly add placeholder text to text inputs, such as your search input field. This text will be removed when the search field is focused, so in effect acts like ye ole JS solutions we've all been using for eons.

Browser support for placeholder looks pretty good, I have it working in Opera 11 and FF4. It should be widely supported in all the next generation browsers.

Drupal 7 gave us alters in the theme layer, so adding attributes to a form item is rather trivial in our themes, no need to build a separate "form alter" mini-module.

This code goes in your template.php file, note this is for the search block only, the advanced search form has a different form_id:

<?php
// Add some cool text to the search block form
function THEMENAME_form_alter(&$form, &$form_state, $form_id) {
  if (
$form_id == 'search_block_form') {
   
// HTML5 placeholder attribute
   
$form['search_block_form']['#attributes']['placeholder'] = t('enter search terms');
  }
}
?>

Adding the placeholder text is very easy, however styling it is not. The text will appear gray and compromises the options for styling the actual text field - contrast issues could ensue.

Webkit and Gecko have interim solutions:

input::-webkit-input-placeholder,
input:-moz-placeholder {
  color: #ffffff;
}

Opera currently has no solution, however it will only be a matter of time before all the next gen browsers support styling placeholder text.

Update

I just found some good information regarding accessibility and the placeholder attribute: http://bit.ly/fa6E0x

Last updated 2nd March, 2011 - 10:25am

Authored by Jeff Burnz on