If you've used Google Chrome you'll have seen the field on the default homepage for searching your history, which looks like this:
On the left is what you see by default. On the right is what you see when you're typing in the field. Notice the default grey text not only vanishes but the text becomes black.
Chrome isn't the only place you see this kind of interface for searching. It's becoming the norm and something users are used to seeing. So, how do we do it?
Here's an HTML version I quickly knocked together:
To see the code behind it download and/or view source of this HTML file. Nothing too complicated! It's a nice and simple way to add some fancy niceness to your applications.
HTML is all very well, but what about if you want to do it in Flex
Although Flex has lots of parallels with HTML I found myself having to stop and think about how I'd achieve the same effect in Flex. I got there without too much re-thinking though, and here's the result:
The code to achieve this is as below:
<mx:Canvas> <mx:Label x="25" y="3" text="Find People" color="#c1c1c1" /> <mx:TextInput id="input" width="120" paddingLeft="20" paddingTop="2" cornerRadius="3" borderStyle="solid" borderThickness="1" backgroundAlpha="0.0" focusIn="input.setStyle('backgroundAlpha',1.0)" focusOut="input.setStyle('backgroundAlpha', (input.text=='')?0.0:1.0)" /> <mx:Image source="@Embed(source='resources/find.png')" x="5" y="3" /> </mx:Canvas>
Notice I've used a Canvas. Elements inside a Canvas are stacked on top of each other in the order they get added. You then position them all absolutely within the Canvas using the X and Y properties of each element. The positions are relative to the top-left of the Canvas itself rather than its parent container! Positioning elements and general page layout in Flex is soooo easy.
Because the Image is the last element inside the canvas it appears on top of the input. Because the Label is the first element it is below the input field. We see it at first because the input field has a background alpha of 0 (transparent). When the input receives focus the background is set to opaque, thus hiding the label. Et voila! A Flex TextInput element with a background image and default text in grey, which is removed on focus (this last sentence is for Google ;-)