Applying a cascading style sheet to a TextArea control in Flex

The following example shows how you can dynamically load a CSS file and apply the style sheet to a Flex TextArea control by setting the styleSheet property.

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/03/22/applying-a-cascading-style-sheet-to-a-textarea-control-in-flex/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white"
        creationComplete="init();">

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

            private var styleSheet:StyleSheet;
            private var urlLoader:URLLoader;

            private function init():void {
                urlLoader = new URLLoader();
                urlLoader.addEventListener(Event.COMPLETE, urlLoader_complete);
                urlLoader.load(new URLRequest("styles.css"));
            }

            private function urlLoader_complete(evt:Event):void {
                var css:String = URLLoader(evt.currentTarget).data;
                // Convert text to style sheet.
                styleSheet = new StyleSheet();
                styleSheet.parseCSS(css);
                // Set the style sheet.
                textArea.styleSheet = styleSheet;
            }

            private function textArea_link(evt:TextEvent):void {
                Alert.show("text: " + evt.text, "Panel");
            }
        ]]>
    </mx:Script>

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

    <mx:TextArea id="textArea"
            htmlText="{txt}"
            editable="false"
            condenseWhite="true"
            width="100%"
            height="100%"
            link="textArea_link(event);" />

</mx:Application>

/src/styles.css

h1 {
    font-size: 24;
}

p {
    font-size: 10;
}

a {
    text-decoration: underline;
}

a:hover {
    color: #FF0000;
}

View source is enabled in the following example.

You can also dynamically load the external .CSS file using the <mx:HTTPService /> tag, as seen in the following example:

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/03/22/applying-a-cascading-style-sheet-to-a-textarea-control-in-flex/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white"
        creationComplete="init();">

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

            private var styleSheet:StyleSheet;

            private function init():void {
                httpService.send();
            }

            private function httpService_result(evt:ResultEvent):void {
                var css:String = evt.result as String;
                // Convert text to style sheet.
                styleSheet = new StyleSheet();
                styleSheet.parseCSS(css);
                // Set the style sheet.
                textArea.styleSheet = styleSheet;
            }

            private function textArea_link(evt:TextEvent):void {
                Alert.show("text: " + evt.text, "Panel");
            }
        ]]>
    </mx:Script>

    <mx:HTTPService id="httpService"
            url="styles.css"
            resultFormat="text"
            result="httpService_result(event);" />
    <mx:String id="txt" source="text.html" />

    <mx:TextArea id="textArea"
            htmlText="{txt}"
            editable="false"
            condenseWhite="true"
            width="100%"
            height="100%"
            link="textArea_link(event);" />

</mx:Application>

/src/styles.css

h1 {
    font-size: 24;
}

p {
    font-size: 10;
    text-align: justify;
}

a {
    text-decoration: underline;
    color: #0000FF;
}

a:hover {
    color: #FF0000;
}

View source is enabled in the following example.

22 thoughts on “Applying a cascading style sheet to a TextArea control in Flex

  1. I would be curious to see if the same styles could be applied to a Rich Text Editor. My understanding is that they cannot be. The best I’ve come up with is to apply a tag along with a color attribute, which presents limitations.

    We’ve found that the inability in the RTE to display hyperlinks leads to a lot of confusion.

    Useful demo of the TA styles (and much appreciated), though.

  2. Seems the RegEx for the blog ate part of my comment…I was using the underline tag in HTML to create the look of a hyperlink.

  3. Thanks for another superb flex example. I have tried using this method with the textarea of a richTextEditor component. I get an error due to the fact that the input text is obviously editable . Is there anyway of applying this method to editable text or is it the fact that it calls the stylesheet at runtime is the problem and therefore would need to parse the css again after editing text? Hope you can help.

    Steve

  4. Hi PeterD,

    I have a situation with external css and a textarea control which is populated with html (styled with classes) drawn from a database. Building on from your example above, the textarea is initially styled correctly. But try loading in new text to replace the text in the textarea after having scrolled. For me the styling bombs out, but what is weird is that it is only after a scroll of the textarea has occurred. I am using flex builder 3.

    Do have any idea why this may be happening?

    Thanks, JP

  5. I am trying to style a TextArea that is called by a Repeater and I keep getting an error that Flex cannot access a property or method of a null object reference. I think it is because the TextArea doesn’t exist until after the stylesheet is called. Any ideas?

  6. Hi Peter,

    I need to apply “vertical-align” to a TextArea and can’t seem to find how to do that anywhere. Can you point me in the right direction?

    Thanks,

    Sean.

  7. Worked like a charm! Thanks, PeterD. One question: I noticed that in your CSS declarations you didn’t have any “px” or other measurement units after the sizes. I’ve tried setting the margin-bottom:10 on an H1 tag, but it won’t take. Any thoughts? It looks like this,

    h4{
    font-size: 14;
    margin-bottom: 10;
    }

    Thanks.

  8. I noticed that after I run this example it works fine. But, if I change the html and/or css, these new changes aren’t applied. Is that because of my problem or that they are ‘cached’ into memory?

  9. Patrick Whittingham,

    I didn’t experiment too much with this entry. You may need to reset the styleSheet property after setting the htmlText property (or vice versa).

    Peter

  10. Patrick,

    You need to set the styleSheet first, and then set the htmlText.

    If you are seeing changes after edits, don’t forget to clean the project. This helps ensure that the newly edited copy of your stylesheet is moved into the bin-debug folder.

    Peter, could you address the vexing problem of trying to print this textfield, populated with htmlText, over multiple pages? I can’t get this to work without losing two lines of text between page breaks.

    I’ve found lots of examples of folks grappling with the printing issue, but no viable solutions. If anyone can find a solution, it would be you!

    David

  11. How to create a styleSheet using the tag <text:StyleSheet>…</text:StyleSheet> ?

    I have tried, but hasn’t succeeded getting it compiled yet.
    The tag is available, so I guess it should be possible.

  12. Heidi,

    Good question. I’m not sure you can define an ActionScript StyleSheet object in MXML. It looks like you’d need to call the parseCSS() method to convert the text into a StyleSheet object.

    http://livedocs.adobe.com/flex/3/langref/flash/text/StyleSheet.html

    This is as close as I could get, but I don’t know it is any better than the code above:

    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application name="TextArea_styleSheet_test"
            xmlns:mx="http://www.adobe.com/2006/mxml"
            layout="vertical"
            verticalAlign="middle"
            backgroundColor="white">
    
        <mx:Script>
            <![CDATA[
                import mx.controls.Alert;
    
                private function textArea_link(evt:TextEvent):void {
                    Alert.show("text: " + evt.text, "Panel");
                }
            ]]>
        </mx:Script>
    
        <mx:String id="cssStr">
            <![CDATA[
                h1 {
                    font-size: 24;
                }
    
                p {
                    font-size: 10;
                    text-align: justify;
                }
    
                a {
                    text-decoration: underline;
                    color: #0000FF;
                }
    
                a:hover {
                    color: #FF0000;
                }
            ]]>
        </mx:String>
    
        <flash:StyleSheet id="styleSh" xmlns:flash="flash.text.*" />
    
        <mx:TextArea id="textArea"
                editable="false"
                condenseWhite="true"
                width="100%"
                height="100%"
                styleSheet="{styleSh}"
                initialize="styleSh.parseCSS(cssStr);"
                link="textArea_link(event);">
            <mx:htmlText>
                <![CDATA[
                    <h1>More Information...</h1>
                    <p>Lorem ipsum <a href="http://www.adobe.com/" target="_top">dolor sit amet</a>, consectetuer adipiscing elit. Donec at arcu in lacus iaculis ultricies. Vivamus consectetuer. Donec vulputate aliquam leo. Nam metus. Aliquam nulla odio, ultrices vitae, nonummy eget, viverra accumsan, tellus. Curabitur neque ante, nonummy ut, fermentum eu, elementum a, ligula. Fusce hendrerit lectus ac velit. Suspendisse lorem pede, sagittis ac, fermentum non, auctor quis, nulla. Integer eu lacus sit amet justo vestibulum sodales. In euismod tellus eget magna. Vestibulum sed ante. Suspendisse eros libero, gravida ac, cursus et, porta vitae, lectus.</p>
                    <br />
                    <p>Vestibulum pretium ante eget justo. <a href="event:flex">Quisque</a> sed tortor nec erat pellentesque sollicitudin. Ut placerat, enim vel ultricies vehicula, leo diam vulputate nibh, eu ultricies dui dui aliquam magna. Phasellus tempus leo eu tortor. Vestibulum sollicitudin turpis et arcu. Nullam felis neque, ultrices eu, vestibulum nec, ornare vitae, odio. Aenean vestibulum ullamcorper justo. Proin magna. Suspendisse potenti. Nunc sodales, eros a ultrices commodo, lorem sem rhoncus eros, id porta arcu felis id massa.</p>
                    <br />
                    <p>Donec tincidunt neque nec erat. In <a href="http://www.onflex.org/" target="_blank">pretium orci vitae justo</a>. Cras massa. Phasellus in massa. Curabitur diam velit, accumsan ut, tristique non, pulvinar in, libero. Praesent et nulla iaculis nisi condimentum tincidunt. Nulla bibendum. Duis pellentesque, libero non hendrerit scelerisque, erat eros dignissim diam, sit amet tempor mi lorem et justo. Curabitur mollis elit vel tortor. Vivamus risus nisl, sodales quis, aliquam non, tempor vitae, nisl. Duis luctus ipsum id felis. Nullam quis dui sit amet ante ultrices gravida. Vestibulum id felis. Curabitur mauris magna, dictum in, accumsan aliquam, bibendum eget, magna. Donec consequat tristique purus. Nunc bibendum nisi vitae tellus. Phasellus elit elit, pharetra id, elementum adipiscing, sollicitudin sed, neque. Nulla arcu. Integer sit amet elit. Pellentesque facilisis, mauris vel ullamcorper faucibus, quam felis fringilla mi, non adipiscing ante odio luctus tortor.</p>
                    <br />
                    <p>Etiam interdum dui quis urna. Cras rutrum ipsum eget nulla vestibulum imperdiet. Proin ut augue porta dui faucibus adipiscing. Pellentesque a dui. Proin malesuada mattis dui. Duis vestibulum, nulla eu hendrerit fermentum, enim purus tristique justo, in aliquet tortor nisl non purus. Nam vitae quam. Duis ut risus ac sem nonummy luctus. Pellentesque a ligula at neque tempus semper. Mauris varius nibh.</p>
                    <br />
                    <p>Nullam consequat justo vitae lorem. Maecenas non dui a eros sollicitudin placerat. Nunc faucibus. Donec vestibulum ullamcorper magna. Vivamus non tellus. Ut quis justo id mi sollicitudin hendrerit. Sed lobortis pharetra turpis. Quisque egestas. Phasellus orci nibh, molestie eu, malesuada semper, imperdiet et, nulla. Vestibulum sed diam. Praesent at justo. Morbi mi eros, ultrices sed, vulputate vitae, varius dictum, est. Donec purus orci, viverra aliquam, sagittis nec, consequat ac, erat. Donec ac justo sit amet erat laoreet semper. Proin ornare. Phasellus adipiscing semper dolor. Nulla ultrices, ante id molestie adipiscing, massa nibh volutpat quam, eget egestas arcu dolor in tortor. Ut laoreet turpis et justo.</p>
                ]]>
            </mx:htmlText>
        </mx:TextArea>
    
    </mx:Application>
    

    Peter

  13. Hi,

    This post is great, the closest yet to the solution that I am searching for. I’m slightly confused as to why I can have custom CSS classes and implement them in Flash or Actionscript projects but cannot do so in Flex. Or, I could be completely off my rocker. Three of us have been using CSS Classes like

    myCustom
    {
    embedFonts: true;
    font-family: “Gotham Bold”;
    font-anti-alias-type:advanced;
    font-size: 12;
    color: #FF0000;
    }

    with html text like

    field.htmlText = <GBodyFX>my css implementation</GBodyFX>

    the TextArea or UITextField will pick up the size, color, basically all the attributes except the embedded font. Now I would say that the font isn’t embedded, but there are components sitting right next to the ones I am having trouble with that are using style properties and look great, embeddedFont, AntiAliasedType.ADVANCED, the whole bit. The only difference are the components that look correct are using compile time CSS and the text components that are using runtime CSS. Any suggestions?

    Thanks!

  14. Hi Everyone

    I have a situation where i have to provide a stylesheeet to the Text Component. So that the htmlText works the sameway as in TextArea, but there is not any property sa stylesheet for Text component.

    Plz suggest how to do implement that.

    Thanks

  15. amarjit,

    I believe this has been fixed in newer versions of the Flex SDK. See http://bugs.adobe.com/jira/browse/SDK-19734 for more information. According to the comments in the patch, this was fixed with SVN checkin 5719 (post Flex SDK 3.3). You can download the latest stable/nightly builds of the Flex 3 SDK from http://opensource.adobe.com/wiki/display/flexsdk/Download+Flex+3 (just make sure you download something more recent than build 3.4.0.5719).

    Peter

  16. Hello everyone,

    I’ve tried the TextArea.stylesheet method and it works, but after applying the stylesheet, it seems that the textarea is not editable anymore?
    I saw that Steve asked the same question, but I did not find an answer to it anywhere.

    I hope someone can help, because I’m in desparate need of an editable textarea with css.

    Thanks in advance,

    Johan Velthuis
    Holland

  17. I’m experiencing the same problem as Johan Velthuis

    It seems that after applying a stylesheet to a TextArea, you can no longer edit the TextArea. What a drag :( But thanks for the great post as usual.

    Andrew.

Comments are closed.