News, ideas and randomness

Using images for background text

Posted: February 7th, 2011 | Author: Scott Barnham | Filed under: web development | No Comments »

Background text: What to type in the field

It’s very common to use ‘background text’ in form fields to indicate what should be typed in there. For example, ‘name’ and ‘email’ in grey text means you should type your, um, name and email address, in to those fields.

The normal way to do it is put text in the fields, set the colour to grey using css and then remove it when the user clicks in that field. It just takes a couple of lines of JavaScript.

But what happens if you want text in a search field, or other field that you want to set the focus on when the page loads?

Background images so the field can have focus

An alternative I’ve used a few times is to have an image containing the grey text and show that image whenever there is no text in the field, regardless of whether the field has focus.

Here’s an example from London taxi booking site Tick Tock Taxi:

The “address, postcode or place of interest” text is a background image and the focus is in that field when the page loads. As soon as the user types something, the image is hidden. If they delete all text from the field, the background image comes back.

A fancier example is from hosting reviews site WhoIsHostingThis.com:

Here the text is typed in after ‘http://‘, so we actually swap between two background images – one with just ‘http://‘ and one which also has the arrow and ‘Enter the domain here‘. It shows an advantage to using images – you can put arrows and other graphics to better explain or draw attention to the field.

Here’s some code.

jQuery:

BackImage = function(field) {
    field = $(field);
    field.bind('keyup', function(e){
        field.toggleClass('empty', field.val() == '');
    });
}

new BackImage('#search_field');

MooTools:

var BackImage = new Class({
    initialize: function(field) {
        this.field = field;
        field.addEvent('keyup', this.update.bind(this));
        this.update();
    },
    update: function() {
        this.field.toggleClass('empty', this.field.get('value') == '');
    }
});

new BackImage($('search_field'));

CSS

The css just sets a background image when the field has class ‘empty’.

#search_field.empty {background:#fff url(../images/bg-search-empty.png) no-repeat 5px center;}

That’s it, a simple technique to have background text while allowing the field to have focus.