Calling actionscript functions through HTML text | asfunction Tutorial

    Add this to the list of things I should have already known!

    Story

    I’ve got an html enabled text box and was trying to devise a way that I could have a hyperlink anchor tag not link to a webpage but actually do something flash. It didn’t seem possible, and I looked through all the different html css combinations I could think of. I finally resorted to trying to use some component like Deng or FlashML. FlashML had a smaller footprint and seemed to do more what I wanted, so I started investigating it. To my dismay, the support for it was few and far between. I found an older version that came with an example file and then a newer one with some documentation but no example and I found no examples any where else. So Lee, if you ever read this, some new examples could be nice. In the documentation I was reading about a functino called AddASFunction and the example html line was very interesting:

    <a href="asfunction:doSomething, startFrame">link</a>

    I started looking through the rest of the documentation to find this asfunction use. But all it had was:
    The href attribute can include the asfunction string which allows the link provided by the anchor to call a function in Flash. More of this can be found within the addASFunction definition in this help document.
    I knew I was on to something, asfunction. So a quick google search and I found the official doc! I was shocked that I had the tool to do this the whole time! Well, shocked and feeling like an idiot for never having heard of it before. I knew it could be done somehow, but had no idea that it was already a feature of htmlText in flash! So now that you know my embarrassing story, I’ll let you in on the secret.

    Overview

    In flash, you can allow html text within a text area. You either set the text html property as true with actionscript (my_txt.html = true;) or click the ‘Render text as HTML’ button in the properties window of the text area. You cannot enable html text on static text areas however. You can have links and various html elements (but not full html). Usually links have a url in the href attribut of the anchor tag, but flash will read a special value of ‘asfunction’ which specifies that an actionscript function is to be called rather than a url. The correct syntax is asfunction followed by a colon and then the name of the actionscript function to be called, optionally followed by a comma and a possible single argument to be passed to the specified function (href=”asfunction:functionName,argument”).

    Steps

    1. Enable html in the text box.
    2. Have your function (ex: functionName) ready to be called from the html link.
    3. Give the href attribute of the anchor tag a property “asfunction:functionName,argument” Notice that the official documentation calls for spaces after punctuation, but any space you put after the colon (:) or comma (,) will be sent to the function in the argument, or will expect a space in the function name and give you a headache.

    Example

    In this example I’ve got an html enabled text box with 4 links. The first is a standard link (I hope you know what that does). The next link calls an actionscript function with asfunction. The third link sends a single argument to another function. And the last link sends multiple arguments to yet another function. Wait! Multiple arguments? I thought I said only one was supported, well this example shows how to send multiple arguments disguised as a single param and parse them. It’s pretty simple actually.

    Get Adobe Flash player

    Actionscript

    import TextField.StyleSheet;

    myHTMLText = "Sample text in an html enabled text box. "+
    "Here's a normal link to <a href='http://circlecube.com' target='_blank'>circlecube</a>! "+
    "And some more links that don't go anywhere, they call functions in actionscript. "+
    "<a href='asfunction:clickLink'>Click this one</a>, "+
    "to see the actionscript function called from the html text box. "+
    "<a href='asfunction:clickWithArg,Click this too'>Click this too</a>, "+
    "and see that the actionscript function you're calling can have an argument passed to it. And "+
    "<a href='asfunction:clickWithMultipleArgs, one,two,three args'>click me three and four</a> "+
    "to see a way to send multiple arguments from your htmlText. "+
    "Also, one last example of what not to do "+
    "<a href='asfunction: clickWithArg, arg with preceding space'>Click for nothing</a>";

    //create and initialize css
    var myCSS:StyleSheet = new StyleSheet();
    myCSS.setStyle("a:link", {color:'#0000CC',textDecoration:'none'});
    myCSS.setStyle("a:hover", {color:'#0000FF',textDecoration:'underline'});

    myHTML.html = true;
    myHTML.htmlText = myHTMLText;
    myHTML.styleSheet = myCSS;

    //function to be called from html text
    function clickLink() {
        giveFeedback("Hyperlink clicked!");
    }

    //another function to be called from html text, recieves one argument
    function clickWithArg(arg) {
        giveFeedback("Hyperlink clicked! Argument: "+arg);
    }

    //a simple trick to allow passing of multiple arguments
    function clickWithMultipleArgs(args) {
        giveFeedback("Hyperlink clicked! Multiple arguments passed: "+args);
        argArray = new Array();
        argArray = args.split(',');
        for (i = 0; i < argArray.length; i++) {
            giveFeedback("arg "+i+": "+argArray[i]);
        }
    }

    function giveFeedback(str) {
        trace(str);
        feedback.text += str +"\n";
        feedback.scroll = feedback.maxscroll;
    }

    HTML

    Sample text in an html enabled text box.
    Here's a normal link to <a href='http://circlecube.com' target='_blank'>circlecube</a>!
    And some more links that don't go anywhere, they call functions in actionscript.
    <a href='asfunction:clickLink'>Click this one</a>,
    to see the actionscript function called from the html text box.
    <a href='asfunction:clickWithArg,Click this too'>Click this too</a>,
    and see that the actionscript function you're calling can have an argument passed to it. And
    <a href='asfunction:clickWithMultipleArgs, one,two,three args'>click me three and four</a>
    to see a way to send multiple arguments from your htmlText.
    Also, one last example of what not to do
    <a href='asfunction: clickWithArg, arg with preceding space'>Click for nothing</a>

    Download Source

    asfunction.zip

    This entry was posted in tutorial and tagged , , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

    12 Comments

    1. Larry
      Posted August 26, 2008 at 4:01 pm | Permalink

      Absolutely awesome, I wasn’t aware – I haven’t had much luck with html text in the past but this is pure awesome. Pure. Multiple argument work-around I hadn’t seen before (or would’ve thought of) either so that’s excellent – thanks for taking the time to share!

    2. Posted December 5, 2008 at 5:33 am | Permalink

      Thanks for sharing. This opens a new world of possabilities!

    3. behived
      Posted December 30, 2008 at 3:46 am | Permalink

      It is maybe a good idea to mention somewhere that it is AS2 only.
      In AS3 you can use a textevent, wich is well explained here

    4. Posted June 23, 2009 at 7:25 am | Permalink

      why is is always a good idea to load .css file at head section? does it speed up the page loading process?

    5. The happy Dane
      Posted July 1, 2009 at 9:33 am | Permalink

      You got to be kidding me! I've been searching for a proper explanation for the asfunction for two whole weeks now and then this, amazing, ingenious little article suddenly appears. GREAT WORK Evan :-)

    6. flax
      Posted August 12, 2009 at 8:15 am | Permalink

      Wow!
      Thanks!
      Great work.

    7. Posted February 26, 2010 at 3:39 pm | Permalink

      This is a great article but this works fine if the text is in the _root level. I use the text in a movie clip (_level1) and it does not work :-( .

    8. Posted February 26, 2010 at 3:40 pm | Permalink

      Sorry guys :-) you have to put the required function in the same level of the targeted level :D good luck

    9. Posted February 26, 2010 at 3:41 pm | Permalink

      Or use _root.functionName :D

    10. Maikel
      Posted March 6, 2010 at 5:50 pm | Permalink

      Thx! Helped me out a lot! :)

    11. Javier Sanchez Conde
      Posted January 18, 2011 at 9:52 pm | Permalink

      I really like your post, is the best example I can found all over the web about this particular issue. But is all in one really short explanation, so thanks again, I still use AS2, because I’m very slow improving my AS2 understanding, maybe because I think is better know it well and later move on AS3. on the other hand I need finish the books I bought when I start with AS. I found that when you got the chance to mix the design with the AS2 on flash the results are better.

    12. Posted November 5, 2011 at 8:32 am | Permalink

      You can also use TextArea class (NOT TEXTAREA THE COMPONENT! it’s a brand new OOP class created by doitflash) instead of using TextField class every where you need to work with text in your AS3 project!

      check out http://www.doitflash.com

      The site produced a class named “TextArea” which is an extension to the original “TextField” class that ends to the shortcomings of TextField.

      TextArea allows you to call your own custom functions right from the hyperlink inside your text block rather than just calling external links or confusing yourself by adding listener when you click the hyperlink, etc… because what if when you want to even pass arguments through your function from your text block, that’s hard but TextArea answers to that too :)

      Here is a sample code to call a function by hyperlink inside your text block:

      import flash.text.TextFieldAutoSize;
      import com.doitflash.text.TextArea;



      // set TextArea
      var _textArea:TextArea = new TextArea();
      _textArea.condenseWhite = true;
      _textArea.autoSize = TextFieldAutoSize.LEFT;
      _textArea.embedFonts = false;
      _textArea.border = true;
      _textArea.multiline = true;
      _textArea.wordWrap = true;
      _textArea.width = 200;

      _textArea.holder = this;
      _textArea.client = this; // must be where you have your 'allowed functions' saved
      _textArea.funcSecurity = true;
      _textArea.allowedFunctions(stringLink, objectLink, arrayLink, arrayObjectStringLink);
      _textArea.mouseRollOverEnabled = true;
      _textArea.fmlText = "<p>Pass String as arguments in this <a href='event:stringLink(simple string)'>link</a>.</p>";



      /*
      my custom functions that I call from _textArea.fmlText by using <a /> tags, like we used to insert hyperlinks inside our text blocks.
      for example, to call stringLink() from _textArea.fmlText, you can write:
      _textArea.fmlText = "my hyperlink: <a href='event:stringLink(this is my passed value)'>link</a>.";

      NOTE: your custom functions arguments can be as many as you like (supported argument types: Object, Array, String)
      */
      function stringLink($value:String):void
      {
          trace("custom function");
      }

      It has lots of more features and doesn’t specifically limited to this issue. Check out doitflash for more information. the site provides the platform and downloading it is also free of charge :)

    Post a Comment

    Your email is never published nor shared. Required fields are marked *

    *
    *

    You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

    • Recent Posts

      WordPress updates plugin directory

      New additions to the plugin directory include: favorites, incorporating support forums into it's own tab for each plugin as well as support stats being displayed! Great! I think we also need the ability to give plugins ratings and reviews (bonus points if it can be done from within a wordpress admin dashboard when installing plugins). [...]

      Short Head

      Use zipf's short head to tune your website rather than redesign the whole thing. To make a website successful it needs to meet the needs of the users. Find out what those needs are by using the short head philosophy to equate most searched things as the biggest needs of the users. Use personas to [...]

      Img Set?

      Great article at a list apart discusing the state of the industry regarding responsive images. This picks apart the set attribute of the img element from a surprisingly objective view coming from someone so close to the picture element. Insightful discussion about the principle behind the proposals than the actual solution too. If the working [...]

      Triudo

      A mesmerizing animated triangle-ish shape form. Embedded Link triduo triduo Tweet

      Git – the paradigm shift

      A great developer story about the differences on what Git is vs other version control and what Git is not. This is how we should learn it. I heard over and over that it was distributed, but never grasped what that meant, so here are a few links and explanations that will help unlearn version [...]

      Tweening Lib comes to Javascript!

      I'm very excited to share the news that the tween library from GreenSock (hands down the best tweening library I used in flash) is not ported for use in javascript! This will be great! I missed that simple syntax from as3 when animating javascript, and now I can have my cake and eat it too. [...]

      Responsive CSS Tricks

      Here are a few useful css tricks to remember when building responsive design sites from web designer wall Embedded Link 5 Useful CSS Tricks for Responsive Design Making the design to be responsive is very easy as shown in my Responsive Design in 3 Steps tutorial, but maintaining the elements to look aesthetically balanced on [...]

      Picture element of srcset attribute?

      Bruce details the reasons and story behind the srcset attribute which is now introduced as an alternative to the picture element. Some aspects of the attribute are nice (like the fact that it's an attribute and not a new element, so it's creating up new elements with for problems. It's adapting currently used elements to [...]

      SVG Preloader with Raphael JS

      Here's a very creative use of using a newly available technology. Using svg graphics which are very lightweight, for a website preloader. I like the animation used as well. Embedded Link Make a stylish preloader with SVG | Tutorial | .net magazine Many sites neglect users with slow connections. Ian Culshaw explains how to use [...]

      CSS3 Button/Icon set

      I've been secretly hoping to see a few of these pop up once the whole icon font idea spread through the nets. I really like this idea and it's a very nice implementation too! I only see some quality issues on a couple of the icons (such as youtube), but it's awesome and I hope [...]

    • Recent Comments

      Bruce Brownlee

      Bruce Brownlee

      Ah IE6. I'd have 2 more years of sleep without IE6. Margin doubling, no properties,...
      versaena

      versaena

      how to give color at runtime…… thank you
      Mobile Websites

      Mobile Websites

      I disagree, mobile websites are the future – desktop websites and mobile websites...
      Matt Fasick

      Matt Fasick

      That's cool. I like the ripple effect as well.
      Nico

      Nico

      hi! really great job guy! very impressive.. just a question… do u have a solution to do a refresh...
      Evan Mullins

      Evan Mullins

      Agreed! I've just seen some people get pretty heated about separating all functionality...