This took forever to google for some reason...
Issue:
You want an input textbox to highlight everything in it when the user clicks it (on focus). Problem is, when the user clicks the text box places the carat, thus un-highlighting the text. I could be wrong, but the second problem seems to be that if you use the FocusEvent.FOCUS_IN event setting selection doesn't work, so you're forced to use MouseEvent.CLICK event... but if you highlight the entire box every time the user clicks, the user can't select any text because it always just highlights the entire box... also, once the box has been highlighted once, you want the user to be able to place the carat without re-selecting the entire box again.
Solution:
What you want to do is check if the user is highlighting or if the box was already highlighted since last focus, and if not, stop flash player from putting the carat at the location clicked with event.preventDefault() function, and then set selection from beginning to end. Event.preventDefault() is a sneaky little function you call right on the event object in your event handler, and it prevents whatever the default actions would be for that event (in this case, clear selected text and place carat)
as3 code example:
// assuming you have a textbox input called _myTextInputBox
import flash.events.FocusEvent;
import flash.events.MouseEvent;
import flash.text.TextField;
_myTextInputBox.addEventListener(MouseEvent.CLICK, onClickTextBox);
_myTextInputBox.addEventListener(FocusEvent.FOCUS_OUT, onTextBoxLoseFocus);
var _highlightTextOnClick:Boolean = true;
function onClickTextBox(e:Event):void {
var didUserHighlight:Boolean = Boolean(e.target.selectionBeginIndex != e.target.selectionEndIndex);
if ( _highlightTextOnClick && !didUserHighlight) {
e.preventDefault();
e.target.setSelection(0, e.target.text.length);
_highlightTextOnClick = false;
}
}
function onTextBoxLoseFocus(e:FocusEvent):void
{
_highlightTextOnClick = true;
}
Posted on
Wednesday, September 23, 2009
by Sean P
filed under