Flash: TextField actionscript hyperlink in AS3.0

by troy on March 14, 2008

In this article we cover how to get flash.text.TextFields HTML anchors/hyperlinks, to call actionscript functions, how to use CSS to style the up, over/hover and down/active and [UPDATE] visited states similar to hyperlinks in normal html, and targetting windows.

The applications of this are numerous. Perhaps clicking a hyperlink will deeplink into your Flash application without navigating away, or perhaps it would open up a dictionary definition on the term.

(Either JavaScript is not active or you are using an old version of Adobe Flash Player. Please install the newest Flash Player.)

Here's the FLA

In this example clicking on the 3 links will show in the bottom text box where the link was meant to go.  This is based on the event handler receiving a flash.events.TextEvent.LINK event, as dispatched by formatting the '<a href=..' to dispatch the link event instead of the default navigateToURL.

The 'blog1' and 'blog2' links both go to the same URL, when either are clicked on both will change to the visited style.   This change color requires a hack, as the 'a:visited' isn't one of the CSS tags supported by Flash.   However we CAN overwrite the CSS style to display a different style, on the click.   This is more complex as we have to figure out, a) are we interested in changing all links that point to that location? or b) just the one that was clicked on?.   Keep in mind that this is a hack, and differs from the way browsers behave in that the links won't persist past that flash session, or across different TextFields unless you code it that way.

You can detect mouseRollOvers using the TextField.getCharIndexAtPoint(x:Number, y:Number) This will return the current character the mouse is over. From there you walk forward and backwards to the end of the word (looking for whitespace), and then presumably do something useful.  You can use for adding graphic end signs which I cover here.

An example with with code of this is at gamelan's site.  Source for a simpler example that highlights text is presented here. What he does in that is search through the body text for the desired word, draw a rectangle to match that words boundaries, place it over the TextField and adjust it's blend properties so that it appears highlighted, that shape could easily have button like properties. Another fun example is his inspiring labs.

In a future article I'll discuss how to clean and process HTML, and replace the links with internal flash link's if you are using CMS'd, progressive enhancement websites, with Flash as the RIA style/presentation layer.  So the same HTML will work as expected when in HTML only site (e.g. for search bots) or in the Flash only.

import flash.text.StyleSheet;
import flash.events.TextEvent;
 
var style:StyleSheet = new StyleSheet();
 
var hover:Object = new Object();
hover.fontWeight = "bold";
hover.color = "#00FF00";
var link:Object = new Object();
link.fontWeight = "bold";
link.textDecoration= "underline";
link.color = "#555555";
var active:Object = new Object();
active.fontWeight = "bold";
active.color = "#FF0000";
 
var visited:Object = new Object();
visited.fontWeight = "bold";
visited.color = "#cc0099";
visited.textDecoration= "underline";
 
style.setStyle("a:link", link);
style.setStyle("a:hover", hover);
style.setStyle("a:active", active);
style.setStyle(".visited", visited);
 
html_txt.styleSheet = style;
var htm:Array = new Array();
htm.push("
 
Example of HTML hyperlinks calling actionscript in AS3.0
 
");
htm.push("
 
 Click to visit <a href="event:http://www.TroyWorks.com">home</a> ");
htm.push("<a href="event:http://www.TroyWorks.com/blog/">blog1</a> ");
htm.push("<a href="event:http://www.TroyWorks.com/blog/">blog2</a>");
html_txt.htmlText= htm.join("");
 
function onHyperLinkEvent(evt:TextEvent):void {
	trace("**click**"+ evt.text);
	define_txt.text = ( "Clicked on " + evt.text);
	var str:String = html_txt.htmlText;
	str = str.split("'event:"+evt.text+"'").join("'event:"+evt.text+"' class='visited' ");
	html_txt.htmlText = str;
 
}
 
html_txt.addEventListener(TextEvent.LINK, onHyperLinkEvent);

Directing the click to specific target
You can redirect a link to a particular window by switching based on the text link e.g.

function onHyperLinkEvent(evt:TextEvent):void {
	trace("**click**"+ evt.text);
     switch(evt.text){
         case "home.html":
         case "aboutus.html":
         case "contactus.html":
                  onHyperlinkClick(evt.text, "_home");
         break;
        case "wiki":
                  onHyperlinkClick(evt.text, "_wiki");
         break;
        default:
                  onHyperlinkClick(evt.text, "_new");
         break;
 
    }
}
//uses 	import flash.net.navigateToURL;
	function onHyperlinkClick(URL : String, target : String) : void {
			trace("onHyperlinkClick " + URL);
			navigateToURL(new URLRequest(URL), target);
		}

{ 23 comments… read them below or add one }

twfan March 16, 2008 at 11:53 pm

Great article, thanks! Is there a way to set a visited link in Flash?

twfan March 17, 2008 at 10:55 am

Thanks, Troy! This a big help. i also appreciate your lightning fast response. This is a great blog. Thanks for all your hard work.

Drew October 20, 2008 at 2:56 pm

Nice article Troy. Do you know of a way to use a rollover script on text links. Something similar to what you currently have, but the hover state allows you to effectively do the same as: html_txt.addEventListner (Event.ROLL_OVER, someFunction, false, 0, true);

troy October 21, 2008 at 12:06 am

Drew I updated the post to give you an approach that might work for you.

Donald December 14, 2008 at 7:43 am

Nice code, thanks !

chris martin February 23, 2009 at 2:35 pm

thanks!! this was helpful

jesal February 24, 2009 at 7:12 am

superb… :))

Drew March 1, 2009 at 4:28 pm

Thanks Troy, Appreciate it (sorry so late – thought I responded)

Attila May 11, 2009 at 4:17 pm

Hello,

Thanks for the great tutorial!

I was wondering if it’s possible to add “_blank” or “target=”_blank” to the links and how? I tried to but no luck. I wanted the links open in a new window.

Thanks!

troy May 11, 2009 at 6:06 pm

Hi Attila, I updated the post to give you an approach that might work for you.

Attila May 13, 2009 at 5:23 pm

Thank you very much! I didn’t understand and couldn’t use the approach you have provided, it’s a bit confusing. I ended up using the regular link AS3 scripts, by making the text as buttons.

Nevertheless, thanks for the tutorial. Maybe I will understand it someday. I am new to AS3.

Alp Tugan October 1, 2009 at 10:09 am

Hi,

I put a link of your tutorial onto my blog page. This is what I’m looking for exactly.

Agustin January 4, 2010 at 11:46 am

Excelent, now I don’t hate using HTML in text fields, exactly what I needed.

Todd January 8, 2010 at 12:09 pm

This has been very helpful.

I am looking for a way to have text indicate an active or down state until another link is chosen.
This would be different than “Visited” because the color would not remain – it would only be active until another link were clicked on.

Please help.

troy January 8, 2010 at 12:49 pm

just use a similar mechanism as how the visited link works. Just clear out the previous one when it changes.

Todd January 11, 2010 at 1:02 am

Troy,

Thanks. I am trying to get through this, and don’t really understand it. Would it be possible to annotate the function, and perhaps write and annotate the clear function as well? Believe me when I tell you that I am in strange water here – have read very little in printed material that gets close to dealing with this, and your blog seems to be the only source of sanity thus far.

I got some errors when trying this out. I used my own htmltextfield variable name in place of html_text but got an undefined variable error for define_txt.

Thanks for the help.

Todd January 11, 2010 at 4:08 am

OK, looked at the FLA and saw the object names – I worked through all of that.

Still, would LOVE to see an example of how to clear things out. The end goal would be to have five separate states… Link, Hover, Active, Visited (you have shown us this neatly, thank you) and a Current or On state, like I mentioned. That way one could see, by virtue of the links, where they have been, where they are right now, and thus where they have left to go.

Sounds like a lot, but I think we have only the one thing left… I just don’t know how to remove the state of Visited.

troy January 11, 2010 at 4:25 am

Unfortunately, I don’t have time to do the work for you and my team is busy on several projects

However a cheap solution is keeping a copy of the original text, then reverting to that copy (and making any additional changes) to clear things out.

Alternatively it’s all about search and replace. If you restyle a link it changes in the html text, you just need to track that and then find and replace it using string manipulation. e.g. textfield_txt.text = textfield_txt.text.split(“”).join(‘link’);

Todd January 11, 2010 at 12:12 pm

Thank you – that was an excellent explanation.

Alex February 4, 2010 at 8:26 pm

Thank you very much!
Your article was extremely helpful to me.
God Bless You!
И заодно привет всем флешерам из Одессы! ))

Mike Petty February 9, 2010 at 9:20 pm

I know this is an old post (sorry about that), but apparently either it’s been around long enough that a regression bug was introduced along the way in either IE or Mozilla (haven’t tried others), or none of us developers caught it by now, or Adobe introduced it in their latest FP 10 runtime.

One of our UAT testers caught this:
Right-click any link, select “Copy Link Location”, it copies the the “event:” preamble that we’re required to use to get a Link to register it as an active link and subsequently dispatch the TextEvent. However since this is in the protected space of the player (I looked in the SDK to see if they were messing with the ContextMenu), it looks like we’re SOL for getting a valid URL onto the clipboard.

Thought I’d point this out, to anyone else frustrated with this bug ;)

troy February 10, 2010 at 12:19 am

Damn that sucks! Definately file a bug for that!!!

sai June 28, 2012 at 1:02 pm

Thanks for this Tutorial. Unfortunately for people like Attila and me it was difficult. After many hours of searching I found a little alternative to this:

http://circlecube.com/2008/06/style-htmltext-with-css-in-your-actionscript-flashcss-tutorial/

Leave a Comment

 

{ 6 trackbacks }

Previous post:

Next post: