Suggested Terms is an excellent usability element which helps the user select a better option or just increase search speed.
In this tutorial, we will learn how to create and display suggested terms in a Flash application.
Step 1: Overview
We’ll make use of TextField and String methods and properties to retrieve and display words from an external file containing the search suggestions.
Step 2: Document Settings
Launch Flash and create a new document. Set the stage size to 500x270px, background color to #F6F6F6 and the frame rate to 24fps.
Step 3: Interface
This is the interface we’ll use, a simple background with a title bar and a two TextFields, an Static TextField telling us what to do and an Input TextField that we’ll use to start suggesting.
No buttons this time, the events will be called by pressing a key.
Step 4: Background
You can leave the background color as it is or add 500x270px rectangle to have something you can select. For the title bar, use again the Rectangle Tool (R) to create a 500x30px rectangle and center it.
Step 5: Title
Select the Text Tool (T) and write a title for your application. I used this format: Lucida Grande Regular, 15pt, #EEEEEE.
Step 6: Text Area
We’ll use a Rectangle shape to show where the TextField is.
With the Rectangle Tool, create a 300x24px rectangle and remove the fill, instead, use a #CCCCCC stroke.
Step 7: Input TextField
Lastly, use the Text Tool to create a 345x20px Input TextField and name it inputField.This is the format I used: Helvetica Bold, 16pt, #666666.
Step 8: Font Embedding
To display the font correctly in the Input Text we’ll have to embed it.
Select the Input TextField and go to the Properties panel, Character section and press the Embed… button.
A new window will come up, select the characters you want to embed, and click OK.
Step 9: New ActionScript Class
Create a new (Cmd + N) ActionScript 3.0 Class and save it as Main.as in your class folder.
Step 10: Package
The package keyword allows you to organize your code into groups that can be imported by other scripts, its recommended to name them starting with a lowercase letter and use intercaps for subsequent words for example: myClasses
. It’s also common to name them using your company’s website: com.mycompany.classesType.myClass
.
In this example, we’re using a single class, so there isn’t really a need to create a classes folder.
package {
Step 11: Import Directive
These are the classes we’ll need to import for our class to work, the import directive makes externally defined classes and packages available to your code.
import flash.display.Sprite; import flash.net.URLLoader; import flash.net.URLRequest; import flash.events.Event; import flash.ui.Keyboard; import flash.events.KeyboardEvent; import flash.text.TextField; import flash.events.MouseEvent; import flash.text.TextFormat;
Step 12: Declare and Extend the Class
Here we declare the class using the class
definition keyword followed by the name that we want for the class, remember that you have to save the file using this name.
The extends
keyword defines a class that is a subclass of another class. The subclass inherits all the methods, properties and functions, that way we can use them in our class.
public class Main extends Sprite {
Step 13: Variables
These are the variables we’ll use, read the comments in the code to find out more about them.
private var urlLoader:URLLoader = new URLLoader();//Used to load the external file private var suggestions:Array = new Array();//The suggestions in the text file will be stored here private var suggested:Array = new Array();//The current suggestions private var textfields:Array = new Array();//A textfield to be used to display the suggested term private var format:TextFormat = new TextFormat();//The suggestions text format private var currentSelection:int = -1;//Will handle the selected suggestion in order to write it in the main textfield
Step 14: Constructor
The constructor is a function that runs when an object is created from a class, this code is the first to execute when you make an instance of an object or runs using the Document Class.
public function Main():void {
Step 15: External File Contents
The terms to suggest will be stored in an external text file, you can also use XML, PHP or the format of your choice.
Write the terms you want to suggest (separated by commas “,” ) and save the file in the same directory as your swf, in this case I used a list of sports and saved them in the file Sports.txt.
Step 16: Load External File
This line calls the load method of the URLLoader class and passes as parameter the url of the txt file we are using.
urlLoader.load(new URLRequest("Sports.txt"));
Step 17: Initial Listeners
Two initial listeners; one listens for the load of the external file and other listens for key up events in the Input TextField.
urlLoader.addEventListener(Event.COMPLETE, loadComplete); inputField.addEventListener(KeyboardEvent.KEY_UP, suggest);
Step 18: Suggestions Text Format
Sets the text format used in the suggestions textfields.
format.font = "Helvetica"; format.size = 12; format.bold = true;
Step 19: Loaded Data
The following function is executed when the external load is complete, it creates an array containing the comma-separated strings in the txt file.
private function loadComplete(e:Event):void { suggestions = e.target.data.split(","); //The split method separates the words using as delimiter the "," }
Step 20: Suggest Function
The suggest function handles all the operations to create and display the suggestions, is executed when the Input TextField detects a Mouse_UP event.
private function suggest(e:KeyboardEvent):void {
Step 21: Reset
The first thing to do is clear the suggested array, this will erase the previous suggestions (if any).
suggested = [];
Step 22: Search Available Data
The next for
loops through the available suggestions and uses an if
statement and the indexOf
method to search for the starting letters of any of the available words.
for (var j:int = 0; j < suggestions.length; j++) { if (suggestions[j].indexOf(inputField.text) == 0)//indexOf returns 0 if the letter is found {
Step 23: Create Suggestions TextFields
If the written letter(s) are found, a new TextField is created for the corresponding word, since we are still in the for
, if more than one suggestion starts with the same letter(s), then many TextFields will be created.
var term:TextField = new TextField(); term.width = 100; term.height = 20; term.x = 75; term.y = (20 * suggested.length) + 88;//Positions the textfield under the last one term.border = true; /* Here we use the border property term.borderColor = 0x353535; to separate the textfields */ term.background = true; term.backgroundColor = 0x282828; term.textColor = 0xEEEEEE; term.defaultTextFormat = format;//Set the previously created format //Mouse Listeners term.addEventListener(MouseEvent.MOUSE_UP, useWord); term.addEventListener(MouseEvent.MOUSE_OVER, hover); term.addEventListener(MouseEvent.MOUSE_OUT, out); addChild(term); textfields.push(term); //Adds the textfield to the textfields array suggested.push(suggestions[j]); term.text = suggestions[j]; //Sets the found suggestion in the textfield } }
Step 24: Clear TextFields
If the user deletes the letters in the Input Field, the suggestions are removed.
if (inputField.length == 0) //input field is empty { suggested = []; //clear arrays for (var k:int = 0; k < textfields.length; k++) { removeChild(textfields[k]); //remove textfields } textfields = []; }
Step 25: Keyboard Control
The next code allows the user to move through the suggestions using the keyboard.
It changes the color of the selected word, adds or removes a number to the currentSelection
variable to use it later in the textfields array, this way it retrieves the correct item from the suggestions.
When the enter key is pressed, the selection is written in the Input Field and the suggestions are removed.
if(e.keyCode == Keyboard.DOWN && currentSelection < textfields.length-1) { currentSelection++; textfields[currentSelection].textColor = 0xFFCC00; } if(e.keyCode == Keyboard.UP && currentSelection > 0) { currentSelection--; textfields[currentSelection].textColor = 0xFFCC00; } if(e.keyCode == Keyboard.ENTER) { inputField.text = textfields[currentSelection].text; suggested = []; for (var l:int = 0; l < textfields.length; l++) { removeChild(textfields[l]); } textfields = []; currentSelection = 0; } }
Step 26: Mouse Control
This function is also used to select the suggestion, although this is easier because of the ability to add event listeners to the TextFields. The listeners were added in the suggest()
function in Step 23, remember?
private function useWord(e:MouseEvent):void { inputField.text = e.target.text; suggested = []; for (var i:int = 0; i < textfields.length; i++) { removeChild(textfields[i]); } textfields = []; } private function hover(e:MouseEvent):void { e.target.textColor = 0xFFCC00; } private function out(e:MouseEvent):void { e.target.textColor = 0xEEEEEE; }
Step 27: Document Class
Go back to the FLA and in the Properties Panel > Publish section > Class field, add Main as value. This will link this class as the Document Class.
Conclusion
You’re done creating and implementing a suggested terms class, it’s time to make your own and customize it! Why not try using PHP to save the terms that users enter to the list of suggested terms?
Thanks for reading this tutorial, I hope you’ve found it useful!