Tuesday, 19 July 2011

AS3: Brand the right-click menu!

Right click menu's are often overlooked and provide a nice touch to any project. Here is a code routine that I've used for many past projects, it should hopefully give you an idea on how to set up a right click menu. for a quick hit use the vars at the top and the last block. The for/switch loops through some items loaded via XML, its code from a live project so perhaps a little verbose.
// context menu
private var nextMenu:ContextMenu;
private var cxLabel:String; 
private var cxTarget:String; 
private var menuItem:ContextMenuItem;

private function setupContextMenu():void {
   nextMenu = new ContextMenu();
   nextMenu.hideBuiltInItems();
   
   for(var i:int = 1; i < 10 ; i++){
     cxLabel = xmlSource.LoaderMax["Item"+i]. @ menuLabel;
     menuItem = new ContextMenuItem(cxLabel);
    
     switch (i){
       case 1:
         menuItem.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, function(e:Event):void { navigateToURL(new URLRequest(links["1-link"]), "_self"); }, false, 0, false);
         break;

       case 2:
         menuItem.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, function(e:Event):void { navigateToURL(new URLRequest(links["2-link"]), "_self"); }, false, 0, false);
         break;

       case 3:
         menuItem.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, function(e:Event):void { navigateToURL(new URLRequest(links["3-link"]), "_self"); }, false, 0, false);
         break;

       case 4:
         menuItem.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, function(e:Event):void { navigateToURL(new URLRequest(links["4-link"]), "_self"); }, false, 0, false);
         break;

       case 5:
         menuItem.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, function(e:Event):void { navigateToURL(new URLRequest(links["5-link"]), "_self"); }, false, 0, false);
         break;

       case 6:
         menuItem.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, function(e:Event):void { navigateToURL(new URLRequest(links["6-link"]), "_self"); }, false, 0, false);
         break; 
      }
      nextMenu.customItems.push(menuItem);
   }
   var menuItemNext:ContextMenuItem = new ContextMenuItem("© 2012 your brand.");
   menuItemNext.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, function(e:Event):void {         
   navigateToURL(new URLRequest("http://www.noursite.co.uk/"), "_self"); }  );
   menuItemNext.separatorBefore = true;
   nextMenu.customItems.push(menuItemNext);
   this.contextMenu = nextMenu;
}

No comments:

Post a Comment