Search code examples
flashactionscriptbutton

Adding a link to a Button in Flash/Actionscript


How do I make a link on a button which is in a Flash movie clip?


Solution

  • Assuming your button has an instance name of "myButton", on the frame where your button is in the timeline, you'll add the following (or similar) Actionscript.

    AS2

    myButton.onPress = function()
    {
       getURL("http://stackoverflow.com", "_blank");
    }
    

    AS3

    import flash.events.MouseEvent;
    import flash.net.navigateToURL;
    import flash.net.URLRequest;
    import flash.net.URLRequestMethod;
    
    myButton.addEventListener(MouseEvent.CLICK, onMouseClick);
    function onMouseClick(event:MouseEvent):void
    {
       var request:URLRequest = new URLRequest("http://stackoverflow.com");
       request.method = URLRequestMethod.GET;
       var target:String = "_blank";
       navigateToURL(request, target);
    }
    

    Backwards compatible getURL for AS3

    /**
     * Backwards compatibility for global getURL function.
     *
     * @param url     Url to go to.
     * @param method  'get' or 'post'.
     * @param target  Window target frame [ex. '_blank'].
     */
    public static function getURL(url:String, target:String = '_blank', method:String = 'get'):void
    {
        method = method.toUpperCase();
        target = target.toLowerCase();
    
        if (method != URLRequestMethod.POST && method != URLRequestMethod.GET) method = URLRequestMethod.GET;
        if (target != "_self" && target != "_blank" && target != "_parent" && target != "_top") target = "_blank";
        var request:URLRequest = new URLRequest(url);
        request.method = method;
        navigateToURL(request, target);
    }
    

    Note that in both AS2 and AS3 you could write this code in a class and set the class as the export class for your button/movieclip. This is probably a bit more complex though.