This chapter will cover the basics of creating, formatting, and interacting with text fields and the text therein. Focusing on the mechanics of using text fields, rather than on string manipulations, this chapter will bring you up to speed with the essentials you need to add text to any project.
Flash uses three different kinds of text fields: static, dynamic, and input. The latter two types can be created and affected by ActionScript; they’re the focus of this chapter. Whenever you wish to exert ActionScript control over text, you turn to a dynamic text field. However, if you require user input, including anything from entering a user name and password to completing an essay, then you need to graduate to an input text field—essentially, dynamic fields with added user input features.
You’ll see in the first recipe of this chapter that you can very easily create a text field, and setting it to behave as a dynamic or input field is simply a matter of using a single property. This capability also means that you can switch between these two types, if the need arises.
The third text type, static, is accessible via ActionScript to a
very limited degree, but only the Flash interface can create static text
fields. You can retrieve text from a static text field, using the
StaticText
or TextSnapshot
classes, but you must walk through
the display list to find the desired field. Additionally, the Flash
interface may break your text into multiple fields after compilation, as
in the case with vertical text, so the ActionScript queries to static text
elements are of marginal use.
You want to create a text field using ActionScript, rather than the Text tool in the Flash interface.
You can create text fields in the same manner as other display
objects, using the new
keyword and
appropriate class, TextField
.
Creating a text field is consistent with creating any other
display object, but setting the type
property of the field determines its functionality. Regardless of
whether you want a dynamic or input text field, new TextField()
is still used to create the
object, and the field must be added to the display list to be visible.
The following example simply creates two different text fields to
demonstrate the use of the type
property.
var score:TextField = new TextField(); score.type = TextFieldType.DYNAMIC; addChild(score); var userName:TextField = new TextField(); userName.type = TextFieldType.INPUT; addChild(userName);
New fields will be added to the display list using all their default properties, including a somewhat awkward 100 × 100-pixel size, so it’s necessary to style the field after creation. In this case, style is a loosely used term for defining basic appearance and functionality.
Use a variety of properties of the TextField
class that apply to the field,
rather than the text therein. Formatting of the text itself is discussed
in a later recipe.
The following script creates and styles a basic dynamic text field. The first block of code creates the text field.
var txtFld:TextField = new TextField(); txtFld.type = TextFieldType.DYNAMIC; addChild(txtFld); txtFld.width = 300; txtFld.height = 20; txtFld.border = true; txtFld.borderColor = 0x666666; txtFld.background = true; txtFld.backgroundColor = 0xCCCCCC; txtFld.multiline = true; txtFld.wordWrap = true; txtFld.selectable = false;
The second block sets the width and height of the text field. This is important because, without this, adding a text field to other display objects conforms those objects to a minimum of 100 × 100 pixels, if the dimensions or size characteristics aren’t changed. This process can be confusing at first, especially in situations where the text must be small, such as in the case of a label for a button.
The third block sets the graphical appearance of the field, manipulating the border and background. Both characteristics are optional and, if turned on, can be colored. This example uses a charcoal border and light gray background.
The last block defines three basic behavioral features of the
field, letting any text the field may contain wrap to multiple lines and
not be selectable. The latter option’s useful when you want to prevent
text selection highlighting from marring a design. If the ability to
select text (to copy to the clipboard, for example) isn’t part of your
product feature set, setting the selectable
property to false is a good way to
override this default behavior.
Finally, one more feature can be helpful in a big-picture way. You can, at the field level, set the color of all text in the field. Setting text color would ordinarily be a formatting task but, if you don’t need character- or word-specific color formatting, you can set text color this way:
txtFld.textColor = 0x660000;
15.1 Creating a Text Field for creating a text field.
You want to hide user input to avoid password entry from being viewable to the casual onlooker.
To display asterisks instead of user input characters, you just
need to use an input field and set the displayAsPassword
property to true
.
var pssWrd:TextField = new TextField(); pssWrd.type = TextFieldType.INPUT; addChild(pssWrd); pssWrd.displayAsPassword = true;
Additional text field properties, however, might also prove
helpful for password input. The maxChars
property limits the number of
characters the user can type in the field, and the restrict
property limits which characters can
be entered. The latter can use limited regular expression patterns to
specify characters, including simple ranges like lowercase
a through z (which converts
all uppercase letters to lowercase) and numbers 0
through 9, as seen in the next code
block.
It also helps to clearly define the size and visibility of the
field so the user can easily find it. Here, width
and height
are specified, as are the use of a
border
and background
.
pssWrd.maxChars = 15; pssWrd.restrict = "a-z0-9"; pssWrd.width = 100; pssWrd.height = 14; pssWrd.border = true; pssWrd.background = true;
Next, let’s create a minimal setup for checking a password. The first two blocks of the following script segment create a button to submit the password. When the button’s clicked, the listener at the end of the script checks the text of the field to see if the text entered by the user matches “actionscript3”. If so, then it traces “success” to the Output panel. If not, then the script empties the field for a subsequent user entry.
var sp:Sprite = new Sprite(); drawSquare(sp, 0x000099); sp.x = 110; sp.buttonMode = true; addChild(sp); function drawSquare(obj:Object, col:uint):void { var g:Graphics = obj.graphics; g.beginFill(col, 1); g.drawRect(0, 0, 14, 14); g.endFill(); } sp.addEventListener(MouseEvent.CLICK, onClick, false, 0, true); function onClick(evt:MouseEvent):void { if (pssWrd.text == "actionscript3") { trace("success"); } else { pssWrd.text = ""; } }
When clicking on an editable text field, the text insert cursor is typically placed into the field, letting the user begin typing. This process is referred to as giving focus to the field. In some instances, however, you may need to accomplish this goal programmatically.
Consider, for example, the previous recipe, in which a user types
a password into an input field. If the password is incorrect, then the
field is cleared, but the user must still click in the field to type.
The following code block adds one new line (shown in bold) to the last
function of the previous recipe, automatically preparing the field for
text entry. It does this step by setting the focus
property of the stage to the text field
reference—in this case, pssWrd
.
function onClick(evt:MouseEvent):void {
if (pssWrd.text == "actionscript3") {
trace("success");
} else {
pssWrd.text = "";
pssWrd.stage.focus = pssWrd;
}
}
The syntax in this new line demonstrates access to the stage through a display object. This line could have been written in a slightly simpler form:
stage.focus = pssWrd;
However, this would work only because the optional this
reference to the main timeline, though
omitted, is implied. The stage is, in reality, being accessed through
the main timeline, a movie clip display object. Using the syntax
featured in the script segment helps remind you that ActionScript 3.0
has no global reference to the stage. You can also remember this
principle by always using the this
reference.
this.stage.focus = pssWrd;
15.3 Creating a Password Field for creating a password field and 13.11 Referencing the Stage Through a Display Object for referencing the stage through a display object.
Use the text
property of the
TextField
class to replace text, or
add text to an empty field. Use the appendText()
method to add text to the end of
an already populated field.
While using the text
property
of a text field isn’t new for ActionScript 3.0, and was demonstrated in
15.3 Creating a Password Field, the new appendText()
method of the TextField class
warrants attention. Briefly, this method achieves the same goal as
txtFld.text += "string value"
, but
much faster. That is, rather than manually appending text to a field
using the compound operator +=
, use
the appendText()
method to accomplish
the same task.
To easily demonstrate this process, start with the field setup from 15.2 Styling a Text Field, and then add the following two lines to your script:
txtFld.text = "I Am"; txtFld.appendText(" the Fly");
The result is the string “I Am the Fly” because " the Fly” was appended to the starting text without overwriting it.
15.2 Styling a Text Field for creating and styling a text field.
Use the autoSize
property of
the TextField
class to resize a text
field based on input and alignment choice.
This recipe continues the previous code example, which has been collected here again for convenience. The first portion of the following script initializes a field and populates it with a single line of text, “I Am the Fly”.
var txtFld:TextField = new TextField(); txtFld.type = TextFieldType.DYNAMIC; addChild(txtFld); txtFld.width = 300; txtFld.height = 20; txtFld.border = true; txtFld.borderColor = 0x666666; txtFld.background = true; txtFld.backgroundColor = 0xCCCCCC; txtFld.multiline = true; txtFld.wordWrap = true; txtFld.selectable = false; txtFld.text = "I Am"; txtFld.appendText(" the Fly"); txtFld.autoSize = TextFieldAutoSize.LEFT; txtFld.appendText(" in the ointment");
The two new bold lines are responsible for adding a second line to
the field, and automatically resizing the field to accommodate. The text
field’s autoSize
property is set to
automatically resize the field, using its left edge as an anchor for
left-justified text. The new line is added using the appendText()
method, but preceding the string
with a new line character,
.
To see the property in action, test the script with and without
commenting the autoSize
instruction.
You find that, despite enabling the multiline
and wordWrap
properties, the field shows only one
line of text without the effect of the autoSize
property.
This outcome occurs because the height of the field is fixed at 20
pixels, so, even with the text spanning two lines, the second line isn’t
visible. The autoSize
property
automatically resizes the field in one or more directions, based on the
setting you use.
The constants of the TextFieldAutoSize
class are LEFT, RIGHT, and
CENTER. If you choose LEFT
as the
autoSize
anchor, then the field
expands or contracts on the right side, as well as the bottom side, in
the case of any new lines or carriage returns. RIGHT
has the opposite effect, resizing to the
left and down, and CENTER
equally
distributes field resizing to the left and right, as well as along the
bottom edge if new lines are added.
In all cases, if the wordWrap
property is turned on, the specified width (or default width, if nothing
is specified) of the field is preserved, and only the bottom edge of the
field is resized. You can see this in action by commenting in and out
the wordWrap
instruction during
testing.
The first part of the following script is similar to several of the previous recipes in this chapter. It creates a dynamic text field, configures basic appearance and functionality attributes, and populates the field.
In this case, two subtle changes warrant comment. First, the height is fixed at 150 pixels, instead of 20, to show multiple lines. Second, text is added to the field with a loop, using a newline character, which ensures that multiple lines exist for scrolling. However, the bolded code, explained following the script, controls the scrolling.
var txtFld:TextField = new TextField(); txtFld.type = TextFieldType.DYNAMIC; addChild(txtFld); txtFld.width = 150; txtFld.height = 150; txtFld.border = true; txtFld.background = true; txtFld.multiline = true; txtFld.wordWrap = true; txtFld.selectable = false; txtFld.text = "I Am the Fly"; for (var i:int = 1; i <= 20; i++) { txtFld.appendText(" " + i + " I am the fly in the ointment"); } this.addEventListener(Event.ENTER_FRAME, onScroll, false, 0, true); function onScroll(evt:Event):void { if (mouseY < txtFld.height/2) { txtFld.scrollV--; } else { txtFld.scrollV++; } }
In this simple example, an enter frame event listener monitors the mouse, and scrolls the text based on the position of the mouse relative to the field. If the mouse is above the horizontal center of the field, the text scrolls up until the top of the field is reached. If the mouse is below the field center, the text scrolls down until the bottom of the field is reached.
If you would rather use a scrollbar to manage text scrolling, you
can easily create a dynamic instance of the UIScrollBar
component. Making sure you have a copy of the component in your
library, you can replace the manual scrolling code (in bold) from the
previous example with the following:
import fl.controls.UIScrollBar; var uiScroll:UIScrollBar = new UIScrollBar(); addChild(uiScroll); uiScroll.scrollTarget = txtFld; uiScroll.x = txtFld.x + txtFld.width; uiScroll.y = txtFld.y; uiScroll.height = txtFld.height;
This first line of this new code block imports the necessary class because component classes are not automatically accessible during compilation. The next two lines create a scroll bar instance and add it to the display list. The next line associates the scroll bar with the desired field. Finally, the remaining lines position the scroll bar at the upper-right corner of the text field, and set the scroll bar’s height to match that of the field.
You can also scroll a text field horizontally. This ability’s
useful when you want to enable long lines without line wrapping—for a
navigation system, perhaps. In the case of manual scrolling, the
principles behind the process are similar, but the scrollH
property is measured in pixels, rather
than lines (as is the case with scrollV
). Proportional typefaces prevent you
from relying on character width for consistent scrolling.
When using the component, you need to set the direction property
of the UIScrollBar
instance to a
horizontal equivalent, as when using the ScrollBarDirection.HORIZONTAL
constant in the
revised code that follows. (Note that you must also import that class if
you plan to use the constant.) You also need to reposition the scroll
bar (to the bottom of the field in this example.
import fl.controls.UIScrollBar; import fl.controls.ScrollBarDirection; var uiScroll:UIScrollBar = new UIScrollBar(); addChild(uiScroll); uiScroll.scrollTarget = txtFld; uiScroll.direction = ScrollBarDirection.HORIZONTAL; uiScroll.x = txtFld.x; uiScroll.y = txtFld.y + txtFld.height; uiScroll.width = txtFld.width;
To see this in action, you can modify the previous script by
replacing the scroll bar code as indicated; changing the width
and height
of the field to narrow and tall (100
and 270, respectively, should work nicely); and setting the field’s
wordWrap
property to false
.
15.2 Styling a Text Field for defining the display attributes and functionality of a text field, and 15.5 Populating a Text Field for populating a text field.
You want to use a custom font, but you want to make sure the font is viewable even on computers that don’t have that font installed.
Using system fonts keeps your files small and efficient, but typically restricts you to using only fonts commonly found in most operating systems. To use a custom typeface reliably, you must use an embedded font so the required font outlines are included in your SWF file.
Furthermore, embedded fonts are required for certain graphical effects, such as rotation and alpha transparency, when used on text fields. Without embedded fonts, text can disappear from fields when these and similar transformations are applied.
To use embedded fonts, you need only one parameter, embedFonts
. The following example code uses
embedded fonts in a hypothetical field called txtFld
. The next few recipes cover specifying
the use of a particular font.
txtFld.embedFonts = true;
In the Flash interface, you can’t embed fonts using only ActionScript. See Chapter 7, for an overview of embedding fonts using the Library panel.
If you enable support for this feature, but fail to specify an
embedded font with the correct linkage class, then the text doesn’t
appear. If this situation occurs, you may be able to quickly test to
see if the embedded font is the problem by commenting out the embedFonts
line of your script and switching
to using a local system font. If the text appears, you can then
investigate the embedding process and correct the problem.
15.9 Formatting Text Using TextFormat through 15.11 Formatting Text Using CSS for specifying font use.
Arguably the simplest way to use ActionScript to format text is to
use TextFormat
instances. Like Cascading
Style Sheets (CSS), you can apply them to many fields, and edits to the
instance are reflected across all its uses. However, TextFormat
instances
are somewhat easier to create.
The first step in formatting text this way is to create a TextFormat
instance. It must exist before
attempting to apply it to a text field. The first block of this recipe’s
code creates the instance, and sets the font and color of the text. It
then turns on bold, italic, and underline, but as separate Boolean
properties to make it easier to mix and match these effects.
The second block controls common type attributes for size,
leading, and letter spacing. All values are in pixels, but the leading
value only applies to the space
between lines of text.
The last block sets the left and right margins as well as the indent of the first line in every paragraph, both in pixels.
var txtFrmt:TextFormat = new TextFormat(); txtFrmt.font = "Arial"; txtFrmt.color = 0x990000; txtFrmt.bold = true; txtFrmt.italic = true; txtFrmt.underline = true; txtFrmt.size = 14; txtFrmt.leading = 4; txtFrmt.letterSpacing = 1; txtFrmt.leftMargin = txtFrmt.rightMargin = 3; txtFrmt.indent = 9;
The next step is to apply the TextFormat
instance to your text field. The
following code block instantiates and populates a text field, and shows
the first way to use the formatter you just created.
var txtFld:TextField = new TextField(); txtFld.type = TextFieldType.DYNAMIC; addChild(txtFld); txtFld.width = 200; txtFld.height = 200; txtFld.border = true; txtFld.background = true; txtFld.multiline = true; txtFld.wordWrap = true txtFld.selectable = false; txtFld.defaultTextFormat = txtFrmt; for (var i:int = 1; i <= 20; i++) { txtFld.appendText("All work and no play makes Jack a dull boy."); }
The for
loop in the last three
lines populates the field with a single paragraph. Immediately before
any text is added to the field, however, the defaultTextFormat
property of the field is set
to the TextFormat
instance you
created. By using this approach, new text added to the field inherits
the formatting. This characteristic is most helpful for formatting an
empty field for user input.
The next approach is to make a one-time change to text that
already exists. Instead of using the defaultTextFormat
property before the text’s
added to the field, you can use the setTextFormat()
method after the field is
populated. To see this change in action, comment out the defaultTextFormat
line in your script to
prevent any initial formatting, and then add the following line after
the loop.
txtFld.setTextFormat(txtFrmt);
The visual appearance doesn’t change because you’re using the same formatting code, but you can use this approach any time, instead of only before adding content to the field.
When formatting existing text, you can also specify a range of
characters rather than changing all text in the field. To do this, you
must add two indices to the setTextFormat()
method, as seen here:
txtFld.setTextFormat(txtFrmt, 43, 85);
The first is the index of the first character to be formatted, and the last is the index of the character after the text you wish to format. That is, the text formatted is firstIndex to lastIndex-1. (This method is a fairly standard way to identify character ranges, and offers the benefit of being able to specify the length of the string as the last index.)
Using TextFormat
instances
doesn’t work on fields that use a style sheet. For more information,
see 15.11 Formatting Text Using CSS.
Use the limited HTML rendering capabilities of text fields.
Flash supports a limited number of HTML tags that you can use to add formatting and functionality to text fields. Table 15-1 lists the tags available in ActionScript, as well as relevant notes, if applicable.
HTML tag | Notes |
| Supported attributes
include: |
| Bold version of font must exist to work. |
| Italic version of font must exist to work. |
| |
| Supported attributes
include: |
|
|
|
|
| All lists are bulleted. Ordered and unordered qualifiers are ignored. |
| Supported attributes
include: |
| Supported attributes
include: |
| Used to apply limited
subset of TextFormat properties to enclosed text. Supported
attributes include: |
To demonstrate that HTML can also be combined with other features for added effect, a simple example will be constructed over the next few recipes. To begin, this script shows the use of paragraph, bold, italic, and font tags to style a line of text. Related upcoming recipes will also make use of span, list, anchor, and break tags.
var txtFld:TextField = new TextField(); txtFld.autoSize = TextFieldAutoSize.LEFT; txtFld.multiline = true; txtFld.selectable = false; addChild(txtFld); txtFld.htmlText = "<p><b>Interactive</b> <i>Text</i> <font color='#FF0000'>Demonstration</font></p>";
Beyond the somewhat restrictive subset of supported tags, working
with HTML is quite straightforward. In the ActionScript 3.0
implementation of HTML, the only point worthy of note is that you no
longer need to first enable HTML support. Simply adding text with the
htmlText
property (instead of the
text
property) automatically makes
HTML features available.
15.11 Formatting Text Using CSS through 15.13 Triggering ActionScript from HTML Links for additional use of HTML.
As with HTML, ActionScript supports a limited set of CSS properties. You can see these properties in Table 15-2. Note that, for consistency, the corresponding ActionScript property names don’t have hyphens.
CSS property | Notes |
| Font color in
|
| Controls display of item.
Values include: |
| Font name. Corresponding
ActionScript property changed to |
| Font size in pixels.
Corresponding ActionScript property changed to |
| Font style. Values
include: |
| Font style. Values
include: |
| Turns kerning on or off.
Values include: |
| Font leading in pixels.
Not officially supported. Similar to: |
| Tracking in pixels.
Corresponding ActionScript property changed to |
| Positions left margin in
pixels. Corresponding ActionScript property changed to |
| Positions right margin in
pixels. Corresponding ActionScript property changed to |
| Specifies text alignment
behavior. Values include: |
| Underlines text. Values
include: |
| Indents first-line
paragraph indent in pixels. Corresponding ActionScript property
changed to |
You have two ways to work with CSS in ActionScript. The first is to create style objects inline, which is covered in this recipe. The second is to load an external CSS document, which will be covered in Chapter 17.
The style sheet’s application is the same in both cases. So, the
basics of the inline method involve creating an object for each style,
and then registering that object with its corresponding HTML tag or CSS
class. The following script creates a simple example style sheet that
contains two arbitrarily named styles for use over the next few recipes.
Together, they demonstrate the use of class-based and tag-based styles.
The first is called task, and is a custom class for
adding emphasis to items or subheads. The second style is called
link, and is associated with the anchor
HTML tag for use in the next two
recipes.
Building on the HTML of the prior recipe, the bold code is new.
The first two segments create custom objects and assign the desired CSS
properties and values. The third segment creates an instance of the
StyleSheet
class, and uses the
setStyle()
method to associate the
objects with the class and tag identifier. Upon completion of this
process, the StyleSheet
instance
css
can be applied to a text field
(discussed following the script).
var task:Object = new Object(); task.fontFamily = "Verdana"; task.fontSize = 14; task.leading = 4; task.letterSpacing = 1; task.textIndent = 14; var link:Object = new Object(); link.color = "#0000FF"; link.textDecoration = "underline" link.fontStyle = "italic"; var css:StyleSheet = new StyleSheet(); css.setStyle(".task", task); css.setStyle("a", link); var txtFld:TextField = new TextField(); txtFld.autoSize = TextFieldAutoSize.LEFT; txtFld.multiline = true; txtFld.selectable = false; addChild(txtFld); txtFld.styleSheet = css; txtFld.htmlText = "<p><b>Interactive</b> <i>Text</i> <font color='#FF0000'>Demonstration</font></p>"; txtFld.htmlText += "<br /><span class='task'>The following tasks are possible:</span>";
The last line of this script is standard HTML fare for using CSS.
A custom class is applied in a <span>
tag that surrounds the desired
text. (The next two recipes use the anchor tag.)
However, the application of the style sheet is noteworthy because
you must apply it before text is added to the
field. This action happens in the first line of the last code block,
before the field is populated with the htmlText
property.
15.10 Formatting Text Using HTML for use of HTML as well as 15.12 Adding Hyperlinks to Text and 15.13 Triggering ActionScript from HTML Links for additional use of CSS.
Use HTML, and an anchor tag, to add the link, similar to the corresponding approach of adding a hyperlink to an HTML page.
Adding standard hypertext links in ActionScript uses the same process as adding links in HTML. The optional target attribute is also supported for opening links in another window.
txtFld.htmlText += "<li><span class='task'>Search: <a href='http://www.google.com'>Google</a></span></li>";
Although this code works on its own if a field called txtFld
already exists, it’s designed to be
added to the previous recipes as an ongoing example. The list tag is
added simply to demonstrate additional use of HTML formatting.
15.10 Formatting Text Using HTML and 15.12 Adding Hyperlinks to Text for information on formatting with HTML and CSS, and 15.13 Triggering ActionScript from HTML Links for additional functionality triggered from HTML links.
Use HTML and an anchor tag to add the link, but use the
ActionScript 3.0 event:
protocol
instead of the http:
protocol, which
is reserved for standard links.
Triggering ActionScript from HTML links in ActionScript 3.0 is
similar to the same process in ActionScript 2.0, but the system now
makes use of the ActionScript 3.0
event model. Previously, the link’s http:
protocol was replaced with asfunction:
and a corresponding function was
typically created for each unique use of this feature.
Currently, the process is similar in that the http:
protocol is replaced with event:
but the corresponding executable code
is less tightly coupled with the link. That is, the link now dispatches
a TextEvent
that can be handled in
the usual event listener manner, granting much more power and
flexibility to the process.
txtFld.htmlText += "<li><span class='task'>Trace: <a href='event:showMsg'> Show Message</a></span></li>"; txtFld.addEventListener(TextEvent.LINK, linkHandler); function linkHandler(evt:TextEvent):void { if (evt.text == "showMsg") { trace("Specific function code executes here"); } }
Although this code works on its own if a field called txtFld
already exists, it’s designed to be
added to the previous recipes as an ongoing example.
15.10 Formatting Text Using HTML through 15.12 Adding Hyperlinks to Text for additional HTML and CSS formatting, and hyperlink use.
You want to programmatically select text in a field, akin to if a user selects the text with the mouse.
The following script passage initializes a field, and populates it with a simple line of text. It then attaches a mouse down event listener to the stage that programmatically selects five characters of that text, characters 6 through 10, thereby selecting the second word, “ipsum.”
var txtFld:TextField = new TextField(); txtFld.width = 200; txtFld.selectable = false; txtFld.type = TextFieldType.DYNAMIC; txtFld.text = "Lorem ipsum dolor sit amet."; addChild(txtFld); stage.addEventListener(MouseEvent.MOUSE_DOWN, onSelectWord, false, 0, true); function onSelectWord(evt:MouseEvent):void { txtFld.setSelection(6,11); }
Remember that text operations like this typically specify a range using the first desired character and the last desired character plus 1. Additionally, the character count is zero-based, with the first character having an index of 0, not 1. See 15.9 Formatting Text Using TextFormat for more information.
The next code block adds another feature that lets you replace selected text with a new string. A similar listener structure is used, this time listening for a mouse up event, and replaces the selection, after first checking to make sure a selection exists. This latter task is accomplished by making sure the beginning and end of the selected text aren’t the same (which would indicate no selection).
stage.addEventListener(MouseEvent.MOUSE_UP, onReplaceWord, false, 0, true); function onReplaceWord(evt:MouseEvent):void { if (txtFld.selectionBeginIndex != txtFld.selectionEndIndex) { txtFld.replaceSelectedText("LOREM"); } }
Finally, if you’ve struggled with text selection and object focus in the past, you’ll be overjoyed to know that ActionScript 3.0 handles this issue quite well. ActionScript 3.0 even has a feature that prevents the selection highlight from disappearing when the field loses focus, as seen here.
txtFld.alwaysShowSelection = true;
To see this feature in action, add the previous line to the end of
the onSelectWord()
function, and
comment out the listener that invokes onReplaceWord()
. (You need to do this step
because, if the word is replaced immediately, you don’t see the effect
of maintaining the selection.) Clicking alternately on the stage and
directly on the text shows the visual difference between when the text
field has focus and when it doesn’t.