Search code examples
actionscript-3apache-flexflex4

Remove focus from input on click outside


I'm using Flex 4.6 with spark components. I have form with DropDownList, and I want to achieve next behaviour:

user clicks on text input in DropDownList -> DropDownList get focus

user clicks outside (on background Rect, for example) -> DropDownList lose focus

Suddenly, second part doesn't work from box. DropDownList still in focus when user clicks outside the text input. How to implement required behaviour?

Example:

<?xml version="1.0"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark">
    <fx:Script><![CDATA[
        ]]></fx:Script>
    <s:TextInput />
</s:Application>

If you click on TextInput it gets focus. And you cannot remove this focus by clicking outside TextInput.


Solution

  • I found solution at the official forum. There is a post with same problem. And working solution in the end:

    textInput.addEventListener(FocusEvent.MOUSE_FOCUS_CHANGE, textInputMouseFocusChange, false, 0, true);
    // basically the above Event will dispatch when ever the user clicked outside of textinput when the current focus in in textInput.
    
    private function textInputMouseFocusChange(event:FocusEvent):void {
    // basically u dont need this first line if u are not calling any function on textInput focusout.
    
        textInput.dispatchEvent(new FocusEvent(FocusEvent.FOCUS_OUT));
    
    // the remaing peice of code will remove the current focus from textInput to the area where the user had clicked.
    // this piece of code i have taken from one of the comments in the blog : http://blog.flexexamples.com/2008/09/23/setting-focus-in-flex-using-the-focus-manager/
    
        var focusPoint:Point = new Point();
        focusPoint.x = stage.mouseX;
        focusPoint.y = stage.mouseY;
        var i:int = (stage.getObjectsUnderPoint(focusPoint).length);
        stage.focus=InteractiveObject(stage.getObjectsUnderPoint(focusPoint)[i-1].parent);
    }