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=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

  • Recent Posts

    WordCamp Presentation Slides: From Photoshop PSD to WordPress Theme

    Here are my slides for my WordCamp Atlanta presentation, From PSD to WordPress Theme: Under the skin: PSD to WP on Prezi Tweet

    wordpress_wordcamp_atlanta_2012_feb_2_3

    Speaker at WordCamp Atlanta 2012

    I’m proud to announce that I’ve been asked to speak at WordCamp Atlanta this year! WordCamp will be held this weekend and hosted at SCAD Atlanta! My session is titled: From PSD to WordPress Theme: Under the skin. Obviously, I’ll be focusing on themes. We’ll look at what they are, what they can do, how [...]

    Adobe-like Arrow Headers | CSS-Tricks

    Zero images is something that always gets me excited, I really like these arrow button styles! I like the css used more and the hover/active states too, nice css3 transitions. via Adobe-like Arrow Headers | CSS-Tricks. Tweet

    snow

    Snow via Javascript & Canvas – Tis the Season

    After playing with the settings in my experiments I found a few settings I liked and wanted to develop further. The first was snow! An added bonus I was able to work on a project just for the holidays and used much of this code in it! I looked around the web and saw a [...]

  • Recent Shares

    Link: Responsive Images: How they Almost Worked and What We Need

    Mat discusses the options for getting responsive images along with responsive designs. We can use various means (server-side, client-side, mobile-first, html5 data attributes, cookies…), but none are fully satisfactory, especially with new browsers prefetching images before cookies can be set or html is even fully read and parsed. He states that bandwidth sniffing is… a [...]

    Screen shot 2012-01-26 at 2.46.59 PM

    Yiibu – About the site…

    Here’s a great article about the process of responsive design & mobile first design and how to practically use them both in a project. This site is a proof of concept for many of the ideas described in Rethinking the Mobile Web or (Mobile First Responsive Design). via Yiibu – About this site…. Tweet

    gridpak

    Link: Introducing Gridpak | Erskine Labs

    Here’s a great tool to make responsive grid layouts. Thanks to Erskine Labs! Introducing Gridpak | Erskine Labs. Tweet

    css-multiply

    Link: HTML5 multiply filter with canvas | Alberto Gasparin

    Here’s a great little script I found useful today as I was working on having dynamic effects applied to javascript via canvas. “The canvas element provides scripts with a resolution-dependent bitmap canvas, which can be used for rendering graphs, game graphics, or other visual images on the fly.” Thanks to the canvas APIs I was [...]

  • Recent Comments

    Karl

    Karl

    I have been using for some time this nice Banner, from developer FX. They have a really nice Live...
    Karl

    Karl

    Thank you for this wonderful link… recommend it! Fast, simple, easy… :-)
    Gabriel

    Gabriel

    Hi Valerie, I don’t know if you are still following this post, but I tried seeing if it is...
    avinash

    avinash

    Hi Evan, I am using the same code and trying it on chrome/firefox it is not working on neither...
    Matt

    Matt

    I needed to store url variables from advertising tracking servers – this method works like a...
    Evan Mullins

    Evan Mullins

    @Saket – you may want to look into swfaddress. I believe it will be more what...