Listening for the link event in a Flex Label control

The following example shows how you can use the link event with the Label control in Flex to handle hyperlinks embedded within a string of text. By using the “event:” prefix in the href property of an anchor (<a />) tag, you can handle links within your Flex application, use the ExternalInterface API to call JavaScript from Flex, or do pretty much whatever else you want.

Full code after the jump.

The Label control must have the selectable property set to true to generate the link event.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/01/26/listening-for-the-link-event-in-a-flex-label-control/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:Script>
        <![CDATA[
            import mx.controls.Alert;

            private function lbl_initialize():void {
                lbl.htmlText = "For more information on Flex, see <u><a href='event:flex.org'>http://www.flex.org/</a></u>.";            }

            private function lbl_link(evt:TextEvent):void {
                Alert.show(evt.toString(), evt.text);

                switch (evt.text) {
                    case "flex.org":
                        // You clicked the flex.org link.
                        break;
                }
            }
        ]]>
    </mx:Script>

    <mx:Label id="lbl"
            selectable="true"
            initialize="lbl_initialize();"
            link="lbl_link(event);" />

</mx:Application>

View source is enabled in the following example.

Another useful little tip when dealing with HTML text, is to put your HTML into an external file, and then embed it into your application using <mx:String />, as seen in the following snippet:

<mx:String id="str" source="text.html" />

<mx:Label id="lbl"
        htmlText="{str}"
        selectable="true"
        link="lbl_link(event);" />

And then your text.html file would look like the following:

<p>For more information on Flex, see <u><a href="event:flex.org">http://www.flex.org/</a></u>.</p>

6 thoughts on “Listening for the link event in a Flex Label control

  1. Hello

    I want to Differentiate the Selected link, with in the Accordion.

    I have a Accordion with 4 levels with the different Links, and updating the Content area by using the Viewstack, Now I want to Highlight the Selected link in the Accordion, showing the user that this is their selection.

    Highlighted can be a Different Text Color or changing the Background Color for the selected link

    Thanks in Advance,
    Prashanth Samanth

  2. That’s good simple sample Thanks.
    Now Is there anyway to sent in parameter(s) with the event somehow?
    So user can dispatch “flex.org” event with a parameter. so it can behave differently. like the parameter will be show in the alert box. Thanks

Comments are closed.