Dynamic Text

Dynamic Text

Flash CS4 ActionScript 3.0 Tutorial

 

How to Output ActionScript Text to the User

 

 

Dynamic text is used to output information from ActionScript to the user.

For more information about other text subjects, see topics, Input Text, Inputting Values and Displaying Results, Setting Text Color and Text Background Color,and Setting Text Font and Size.

In this example we will create a random number generator. Each time the user presses the Roll button, another value is displayed in the Dynamic text field.

Tutorial Elements

Dynamic Text box with instance name of outText_txt

Button Symbol with instance name of roll_btn

 

Step One

Open a new Flash document and add a new layer.

Step Two

Name the upper layer Actions and the lower layer Content.

Step Three

Click the keyframe for the Content layer.

Step Four

Add an empty Dynamic text block to the stage. Choose Dynamic text In the Properties panel.

Step Five

Click the Dynamic text box and assign it an instance name of outText_txt in the Properties panel.

Step Six

Add a button symbol to the Content layer and assign it an instance name of roll_btn in the Properties panel. For more information on creating buttons, see topic, Button Symbol Basics.

Step Seven

Option double-click (PC - Alt double-click) the keyframe of the actions layer to open the ActionScript panel.

Step Eight

Copy/Paste the following code to the ActionScript panel.

var rollValue:uint = 0;

roll_btn.addEventListener(MouseEvent.CLICK, newRoll);

function newRoll(e:MouseEvent):void{

rollValue = 100*Math.random();

outText_txt.text = String(rollValue);

}

Step Nine

Click the Auto Format button to format the code

Step Ten

Test your movie by pressing Cmd/Return (PC - Ctrl/Enter). Each time you press the Roll button, a new random number displays in the Dynamic text field.

Dissecting the Code

The first line of code establishes a new positive integer variable named rollValue and sets its value to zero. The next line adds an Event Listener to the button. It needs to know if the button has been clicked. Once the user clicks the button, the function newRoll is told to run.

The code inside the curly braces of the function determines what the function will do. The rollValue line creates a random number between zero and one. That number is multiplied by 100 so your random values are whole numbers between zero and 100.

The final line of code interprets the rollValue as a String and places that value in the Dynamic text field with the instance name of outText_txt.

 

Royalty-Free Stock Video at Pond5