rss twitter

Automatically select all Text on Focus

Hi, I've just tried to get the following to work:
There's a dynamic textfield on stage which holds some text. I wanted to achieve a "Select all the text as soon as the user (single-)clicks on it" - this surely is a bit unorthodox, but there was a reason for that. At first I didn't think of any problems that could occur, but as usual I was surprised by Flash again.

So whoever on this earth comes to this situation - you're not alone. Just read on..

To sum it up I just want to tell you, that the following code does not work (as I supposed it to do):

Actionscript:
  1. titleTF.addEventListener(FocusEvent.FOCUS_IN, onFocusIn);
  2.  
  3. function onFocusIn(event:FocusEvent):void {
  4.     event.target.setSelection(0, event.target.text.length);
  5. }

Instead you've got to use a slight delay before calling the setSelection method, otherwise the TF's internal FocusEvent (set cursor) comes after the selection and resets it. So there won't be any text selected at all. Here's a working solution on that:

Actionscript:
  1. titleTF.addEventListener(FocusEvent.FOCUS_IN, onFocusIn);
  2. titleTF.addEventListener(FocusEvent.FOCUS_OUT, onFocusOut);
  3.  
  4. function onFocusIn(event:FocusEvent):void {
  5.     setTimeout(event.target.setSelection, 50, 0, event.target.text.length);   
  6. }
  7.  
  8. function onFocusOut(event:FocusEvent):void {
  9.     event.target.setSelection(0,0);
  10. }

Not sure if anyone will ever need this :) But we'll see..

One Response to “Automatically select all Text on Focus”

  1. LewisF says:

    besides it's really not too useful it's good to know. :-)

Leave a Reply

Powered by WordPress | Free T-Mobile Phones for Sale | Thanks to Palm Pre Blog, Video Game Music and Get Six Pack Abs