Wind Chimez
Wind Chimez

Reputation: 1176

Preventing navigation via clicking anchor link in Actionscript

I am creating a textbutton using actionscript. the code is given below.

public function createTextButton(parentId){
            var mytext:TextField = new TextField();
            mytext.x = 478;
            mytext.y = 225;
            mytext.height = 20;
            var format:TextFormat = new TextFormat();
            format.font = "Hitchcock";
            format.size = 20;
            mytext.defaultTextFormat = format; 
            mytext.textColor =  0xffffff;
            mytext.htmlText = '<a href="j#" >Click Here</a>';

            mytext.addEventListener(MouseEvent.CLICK,paginationLinkClicked);
            mytext.addEventListener(MouseEvent.MOUSE_OVER,mouseOverButton);
            mytext.addEventListener(MouseEvent.MOUSE_OUT,mouseOutButton);
            parentId.addChild(mytext);  
        }

Now i want the click event of this button to be handled in my event handler function only. It should not navigate away to the 'href' source given upon clicking. How can i achieve that.

Upvotes: 1

Views: 218

Answers (1)

Sam Dolan
Sam Dolan

Reputation: 32532

Add event.preventDefault(); in your event handler once you've finished your custom handling.

From the adobe docs: http://livedocs.adobe.com/flex/3/langref/flash/events/Event.html

flash.events.Event.preventDefault(): Cancels an event's default behavior if that behavior can be canceled.


Update:

preventDefault won't work in this case.

You'll need to add a link event handler and prefix the url with event:. Here's a simplified version of your code:

public function createTextButton(event:Event):void
{
    myText.htmlText = '<a href="event:j#">Click Here</a>';
    myText.addEventListener(TextEvent.LINK, handle_linkClick);
}

protected function handle_linkClick(event:TextEvent):void
{
    var linkText:String = event.text; // Will give you everything after `event:`. In your case: "j#"
    // Custom code goes here....
}

TextArea docs on the link event handler:

Dispatched when a user clicks a hyperlink in text defined by the htmlText property, where the URL begins with "event:". The remainder of the URL after "event:" is placed in the text property of the link event object.

When you handle the link event, the hyperlink is not automatically executed; you need to execute the hyperlink from within your event handler. You typically use the navigateToURL() method to execute the hyperlink. This allows you to modify the hyperlink, or even prohibit it from occurring, in your application.

Upvotes: 2

Related Questions