Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > Adobe Flash

Creating Custom Context Menus in Flash MX 2004

  • Print
  • + Share This
This article shows you how to create custom context menus for your Flash movies using Macromedia Flash MX 2004.
Like this article? We recommend

The context menu is the menu that appears when you right-click (Control-click on a Macintosh) on a Flash movie.

NOTE

For brevity sake, for the remainder of the lesson we will be only be referencing right-click functionality for the opening of a Flash context menu. It should be understood that Control-clicking on a Macintosh is the equivalent to right-clicking on a Windows computer.

There are three different types of Flash context menus:

  1. The one that appears when you right-click on the anything in a Flash movie except a text field. This is called the standard menu.

  2. The one that appears when you right click on a text field that is editable or selectable. This is called the edit menu.

  3. The one that appears when a Flash movie fails to load within a web page and you right click in the empty area. This is called the error menu.

Both the standard and edit menus are customizable. The error menu cannot be changed. The context menus can be customized to display new items or remove the built-in default items. All built-in context menu items can be removed except for the Settings item and the Debugger item.

Figure 1Figure 1 There are two classes built-in to the Flash player which there to assist you in creating a customized context menu:

  • The ContextMenu class. This class allows you to create a brand new context menu, hide built-in menu items (Zoom In, Zoom Out, 100%, Play, Stop, etc.), and keep track of customized items.

  • The ContextMenuItem class. Each item in a context menu is an instance of this class. The ContextMenu class has a property (array) called customItems. Each element in that array is an instance of the ContextMenuItem class.

The ContextMenu class and the ContextMenuItem class are used together to build custom context menus.

Figure 2Figure 2 When creating a new instance of the ContextMenu class you can specify a function to be called when that ContextMenu is displayed.

var myContextMenu:ContextMenu = new ContextMenu(menuHandler);

Just before the context menu appears the menuHandler() function is executed. As a result of the function executing before the menu actually appears, script within the function can be used to evaluate certain conditions within the application, and items on a context menu can be dynamically added, removed, enabled, or disabled. For example, a "Save" item may be disabled if nothing has changed since the last time the user saved.

You can dynamically change the function a context menu calls before it appears, by redefining its onSelect event handler. For example:

myContextMenu.onSelect = anotherFunction;

As a result of this script, myContextMenu will now call anotherFunction() when it is selected (before it appears) instead of menuHandler(), as was defined when the ContextMenu object was initially created.

When creating custom context menus, you may wish to remove the default items that appear. To hide the built-in items in a context menu you must call the hideBuitInItems() method:

myContextMenu.hideBuiltInItems();

All built-in items will be hidden from the context menu except the Settings and Debugger items. Also, in editable text fields, the standard items such as Cut, Copy, Paste, Delete, and Select All are not removable.

Instances of the ContextMenu class have only one property, customItems. This is an array that stores the custom ContextMenuItem objects that form the custom items that appear on the menu. To add a custom item to a ContextMenu object, you must add it to the customItems array for that object:

myContextMenu.customItems.push(new ContextMenuItem("Next Page",
 nextPageHandler));

This adds a new ContextMenuItem object to the customItems array of the myContextMenu object. The first parameter is the text that will be displayed in the menu. The second parameter is the callback function for that item. When the item is selected from the context menu, the callback function (nextPageHandler()) is called.

Figure 3Figure 3 Custom menu items in a context menu can be referenced like this:

myContextMenu.customItems[0] // first custom menu item
myContextMenu.customItems[1] // second custom menu item
myContextMenu.customItems[2] // third custom menu item

Knowing this, you can enable and disable menu items dynamically:

myContextMenu.customItems[1].enabled = false;
myContextMenu.customItems[3].enabled = false;

Disabled menu items will still appear on the custom context menu, but they will appear grayed-out and will not function when clicked. Menu items are enabled by default.

You can dynamically change the function a context menu item calls when it is selected, by redefining its onSelect event handler. For example:

myContextMenu.customItems[0].onSelect = differentCallbackFunction;

NOTE

Just to clarify, a context menu itself has a callback function that is executed just before the menu appears, and context menu items also each have a callback function that is executed when that item is selected from the menu.

To use a custom context menu, it has to be assigned to a particular movie clip, button, or text field instance. Doing so will cause that custom menu to appear when the instance is right-clicked. Here's the syntax:

myClip_mc.menu = myContextMenu;

When the mouse is right-clicked while above the myClip_mc movie clip instance, the myContextMenu context menu will be displayed.

NOTE

A single custom context menu can be associated with as many movie clip, button and text field instances as you wish.

When using custom context menus, it's important to be aware that the timeline with the highest depth always captures the right-click mouse event, which causes its custom menu to be displayed. For example, if two movie clips are overlapping and each has a custom context menu associated with it, then the one that is at a higher depth is the one whose menu will be shown when the mouse is right-clicked above it. This goes for the main timeline too. If the mouse is not over a movie clip that has a custom menu but the main timeline (_root) does, then its menu will be displayed.

In this exercise you will create a custom context menu with several custom item used to print and manage the contents of an editable text field.

1) Open ContextMenu1.fla.

This file has three layers, Background, Text Field, and Actions.. The Background layer contains the graphics for the project. The Text Field layer contains an input text field instance with a name of entry_txt. Frame 1 of the Actions layer is where you will add the ActionScript for this project.

When complete, you will be able to add text to the editable text field, and then right-click to either print, delete or reformat the text.

2) Select frame 1 in the Actions layer, open the Actions panel, and add this line of ActionScript to create a new instance of the ContextMenu class

var myContextMenu:ContextMenu = new ContextMenu(menuHandler);

This code creates a new instance of the ContextMenu class named myContextMenu. This custom context menu will eventually be associated with the entry_txt text field, so that when the mouse is right-clicked over that field, this menu (and the menu items we will eventually add to it) will appear. We are going to add three custom items to this menu that will enable the user to:

  • Print what's in entry_txt field

  • Delete any text in the entry_txt field

  • Reformat any text in the entry_txt field so that it's red in color and consists of all uppercase characters.

In the constructor , a reference to a function called menuHandler() is passed in. This function will be called whenever this menu is opened (the user right-clicks on the entry_txt text field). Let's create that function next.

3) Add the menuHandler() function definition below the current script:

function menuHandler() {
 var numberOfItems = myContextMenu.customItems.length;
 if (entry_txt.text.length > 0) {
   for(var i = 0; i < numberOfItems; ++i){
    myContextMenu.customItems[i].enabled = true;
   }
 } else {
   for(var i = 0; i < numberOfItems; ++i){
    myContextMenu.customItems[i].enabled = false;
   }
 }
}

This function will be called just before the myContextMenu menu appears. The purpose of this function is to enable and disable custom items on that menu on-the-fly, depending whether there is currently any text in the entry_txt text field. In other words, if there is text in that field, custom items on our context menu will be enabled, otherwise, if it contains no text, items will be disabled.

The first thing the function does is creates a variable named numberOfItems. The value of this variable is based on the number of custom menu items that have been added to the myContextMenu instance. In the case of this project, that instance will eventually have three items added to it, thus the value of numberOfItems will be 3. The value of this variable will be used in a moment.

Next, a conditional statement is used to evaluate whether the user has entered any text into the entry_txt text field. If the field does contain text, the first part of the statement uses a loop to quickly enable all the custom items on the myContextMenu instance. If no text is found, then all the items are disabled.

Figure 4Figure 4 After this function has executed, the menu will appear. Let's next add some custom items to the myContextMenu instance:

4) Add this line of script, just below the menuHandler() function:

myContextMenu.customItems.push(new ContextMenuItem("Print Fridge Note",
 printHandler));

This line of script adds a new ContextMenuItem instance to the customItems array of the myContextMenu instance. This defines the first item that will appear when the menu is opened.

The first parameter of the ContextMenuItem constructor method contains the text that we want to appear in the menu representing this item. The second parameter is the callback function that should be executed when the item is selected. This function will be created next.

5) Add this script to define the printHandler() callback function:

function printHandler() {
 var myPrintJob:PrintJob = new PrintJob();
 var result:Boolean = myPrintJob.start();
 if (result) {
   myPrintJob.addPage("entry_txt");
   myPrintJob.send();
 }
 delete myPrintJob;
}

This function is called when Print Fridge Note is selected from the context menu. The first line creates a new instance of the PrintJob class. The second line attempts to initialize the printer. It captures the result of printer initialization. If the printer does not exist or if the user cancels the print request, then the result variable has a value of false. If the user proceeds with the print request then the result variable is set to true.

If result is true, then we use the addPage() method of the PrintJob class to add the entry_txt text field to be printed. The remaining default parameters for the addPage() method are acceptable, so we do not need to set them.

Next, the page is sent to the printer and then the myPrintJob instance is deleted.

Let's add the remaining two items to our custom context menu.

6) Add this script to the end of the current script:

myContextMenu.customItems.push(new ContextMenuItem("Clear Fridge Note", 
clearHandler));
function clearHandler() {
 entry_txt.text = ""
}

This adds another custom item to the customItems array of the myContextMenu instance. Clear Fridge Note will appear as the text for this item, and the clearHandler() function is called when this item is selected. That function is created with the three remaining lines of script. Its only task is to remove any text from the entry_txt text field.

7) Add this script below the current script:

myContextMenu.customItems.push(new ContextMenuItem("Urgent Fridge 
Note", urgentHandler));
function urgentHandler() {
 entry_txt.textColor = 0x990000;
 entry_txt.text = entry_txt.text.toUpperCase();
}

This adds one more custom item to the myContextMenu instance. As you can see, the text for this item is, Urgent Fridge Note, and the function called when this item is selected is named urgentHandler(). This function takes the text entered into the entry_txt field, colors it red, and converts it to all uppercase characters.

8) Add this final line of script:

entry_txt.menu = myContextMenu;

This associates the myContextMenu instance with the entry_txt text field. If the mouse is right-clicked on anything but this text field, then the custom context menu will not be shown. If the mouse is click on the text field, then the custom menu will be displayed.

9) Select Control > Test Movie to test your work. Type into the text field. Bring up the custom context menu and select a custom menu option.

Figure 5Figure 5 You'll notice that if the text field is blank that the custom menu items are not enabled in the context menu. They are still there, but are not selectable. If the text contains at least character of text, then the menu items become available. This is the result of the menuHandler() function created in Step 3.

10) Close the Test Movie and save your work as ContextMenu2.fla.

This completes the exercise.

As you have learned, custom context menus open up an entirely new way for users to easily interact with your application, without having to manually search for a particular button or control. Be aware that most users are not familiar with this new feature of Flash, so if you do use it, be sure to make them aware of it.

  • + Share This
  • 🔖 Save To Your Account

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Peachpit products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email ask@peachpit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.peachpit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020