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

    Developing for old browsers is (almost) a thing of the past – (37signals)

    Basecamp announces that it’s new version will not support old browsers! They will of course continue to support them in their “classic” version. But this is good news and as more implement this type of policy the internet will be happy. It used to be one of the biggest pains of web development. Juggling different [...]

    Screen shot 2012-02-10 at 12.59.33 PM

    Vendor Prefixes – about to go south

    What are “standards” coming to? Who’s guilty? Apple and Chrome: They’re supporting vendor prefixed properties like they’re a standard part of development. Firefox, Opera and Internet Explorer: They should have been on the ball more. Need to push their evangelism further. Teach developers that it’s not exclusively -webkit to style elements. All the browsers: experimental [...]

    bio

    An Event Apart Notes: Ethan Marcotte, Responsive Web Design

    Ethan Marcotte has become the father of Responsive Web Design and spent this whole day focused on principles, techniques, gotchas, examples, … all about building and how to build responsive sites. With a sprinkle of mobile first. For Ethan, it all started with this article: http://www.alistapart.com/articles/dao/ Think of architecture, the whole design phase is established [...]

    Webcomm_Montreal

    An Event Apart Notes: Jared Spool, The Curious Properties of Intuitive Web Pages

    Senseless waste of asterisks… Avis used an asterisk to denote optional fields. This means that there is a lot of baggage that comes with an asterixk. Somewhere this symbol got meaning, it’s not in the bible! We can control when something goes from unintuitive to intuitive. A design is intuitive (although technically and grammatically speaking [...]

    untitled-158-2

    An Event Apart Notes: Marco Arment, Bridging the App Gap

    The iPhone changed our industry in 2007: first mobile to have a desktop class web browser and it made people start using their mobile phones as computers! All apps other than apple provided ones were web browser apps. Most of the first apps were branded web browsers. No real difference between using mobile site or [...]

    lukew_space

    An Event Apart Notes: Luke Wroblewski, Mobile to the Future

    MASS MEDIA (in waves) Print, Recordings, Cinema, Radio, Television, Internet, Mobile Mobile is the new Mass Media It certainly is mass and massive. More mobile devices (by far) every day than babies born on the planet. Mobile devices are eating into our personal computing shares. New waves of mobile media eat all previous media waves. [...]

    IMG_4500

    An Event Apart Notes: Josh Clark, Buttons are a Hack

    Mobile and touch should be revolutionizing design and user experience. We don’t want to touch a tiny link or button. Back button is just stupid. Fitz’s Law, make things fat proximal targets for easy touching. People are lazy, let’s as designers LET people be lazy! Maybe even use the whole screen as your control. Eliminate [...]

    nicole_pink_bkg_2012

    An Event Apart Notes: Nicole Sullivan, Our Best Practices are Killing Us

    Grep to for analyze css. CSS duplication is a web-wide problem. Started helping facebook optimize thier site and they had 1.9MB of css loading. The same color showing up hundreds of times. Many many color statements and declarations. !important declarations get dangerous. Sites found to have over 500 !important declarations! float is a serious problem [...]

    ericmeyer

    An Event Apart Notes: Eric Meyer, The Future of CSS

    Cormorant trained to fish for the fishermen. The fishermen tie bands around the birds necks that are. Fishermen fish at night, using lamps they attract bugs, which attract fish, and the cormorant get to fish but cant swallow them and the fishermen take the fish. Browser vendors are promising us new CSS tools, but don’t [...]

    sammyj

    An Event Apart Notes: Ethan Marcotte, Rolling Up Our Responsive Sleeves

    Henry Adams (Descendant of 2 presidents: great-grandson to John Adams and grandson to John Quincy Adams). He lived between the civil war and world war 1. He witnessed the industrial revolution. Chaos was the law of nature, Order was the dream of man Samuel Johnson – funniest man in the 17th Century… Responsive Design: 1. [...]

  • Recent Comments

    me-gamer

    me-gamer

    this is really nice. this made many of my task simple.
    Lori Newman

    Lori Newman

    Just wanted to thank you for your presentation. It was extremely informative and just what I...
    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...