I’ve been asked a few times by folks on ways to effectively add a background image to a search input field. This technique is used on the Apple website.
I always thought it was a cool ‘bells and whistles’ type feature and decided to try to implement this on some projects myself.
There are only two styles to use. One sets the background image and padding for the image on the field before the user clicks in the field. The second style, which is applied to the input field itself, is called when the user’s cursor is focused on the field. (The blinking cursor when you click in the box.)
As you can see there’s not much to it. The searchBox class is displaying the magnifying glass image at the far left of the field with a padding of 20px.
The input style is defined with no background image. This is the effect that removes the icon when the user clicks inside the field. We set the width 20px larger to avoid the field shrinking onblur. This is important. Without the extra width the field will shrink onblur and the effect will look less than professional.
We’ll focus on the onfocus part first. Here we are accessing the DOM to reference the ID ‘searchField’ and set the class via the setAttribute call. Since we want the icon to disappear when the user focuses on the text field, we set the class to none. This applies the input style above.
The next item is onblur. We again access the field through the DOM reference of ID. But this time we add a class to the input field, in this case .searchBox. This adds the icon back into the field which results in a nice clean ‘bells and whistles’ effect.
The good thing about this technique is that is does not add much markup to your code and can still offer something to your end users. It’s nice to have eye candy on your pages but using them effectively where it doesn’t inhibit your users experience is the key.
[button type=tick color=whitesize=normal]Demo[/button]