Click here to Skip to main content
Click here to Skip to main content

JavaScript Context Menu Control

By , 23 Jun 2008
 

demo.gif

Introduction

I’m going to introduce here a JavaScript Context Menu control. It is a cross-browser JavaScript class that runs on various browsers except Opera as Opera doesn’t support the oncontextmenu event.

Background

Around one and a half years ago, I had created a context menu to display on a GridView control to perform some actions in a project. That project was IE based. So, the context menu was IE specific, and not cross-browser compatible. Also, it was a mixture of JavaScript and HTML: I had created its layout using the HTML table and div elements and displayed it using JavaScript. I wanted to develop it as a cross-browser JavaScript class. So, I started its development, and after spending some time on the Internet and books, I succeeded.

Constructor

The constructor of the context menu class takes an argument of the type Object Literal. The definition of the Object Literal argument for this control is given below:

var Arguments = {
   Base: _Base, // Base reference where Context Menu to be displayed.
   Width: _Width, // Width of the Context Menu in integer.
   FontColor: _FontColor, // Font Color of each Context Menu item.
   HoverFontColor: _HoverFontColor, // Hover Font Color of each Context Menu item.
   HoverBackgroundColor: _HoverBackgroundColor, // Hover Background Color
                                                // of each Context Menu item.
   HoverBorderColor: _HoverBorderColor, // Hover Border Color of each Context Menu item.
   OnClickEventListener: _OnClickEventListener // Reference of the click event handler.
};

//Example:

var Arguments = {
   Base: document.getElementById('div'),
   Width: 200,
   FontColor: black,
   HoverFontColor: white,
   HoverBackgroundColor: blue,
   HoverBorderColor: orange,
   OnClickEventListener: ClickEventHandler  
};

You can assign each property of the Object Literal argument to null. In this case, each property will acquire its default value as:

var Arguments = {
   Base: null, // Default Value: document.documentElement.
   Width: null, // Default Value: 200.
   FontColor: null, // Default Value: ‘black’.
   HoverFontColor: null, // Default Value: ‘white’.
   HoverBackgroundColor: null, // Default Value: '#2257D5'.
   HoverBorderColor: null, // Default Value: ‘orange’.
   OnClickEventListener: null //Default anonymous method.
};

Methods

The context menu control has the following public methods:

  • AddItem(ImagePath, ItemText, IsDisabled, CommandName) - Used to add a context menu item.

    It takes four arguments:

    • ImagePath: Path of the item image.
    • ItemText: The item text.
    • IsDisabled: Indicates whether the item is to be disabled or not.
    • CommandName: The command name of the item.
  • AddSeparatorItem(): Used to add a separator item.
  • Display(e): Used to display the context menu.
  • Hide(): Used to hide the context menu.
  • Dispose(): Used to destroy the context menu.
  • GetTotalItems(): Used to get the count of total items including the separator items.

Properties

The context menu control has only a public property. It only displays the current version of the context menu control. It does nothing else.

  • Version: Displays the current version.

Events

The context menu control has only one event – The Click event that fires when items other than the separator items are clicked.

  • Click: Fires when an item is clicked.

The local anonymous method that responds to the Click event (i.e., the event handler) has the following signature:

var EventHandlerName = function(Sender, EventArgs)
{
   ...
}

where Sender is the reference of the element that raises the click event (i.e., the tr element) and EventArgs is the Object Literal that contains the necessary information regarding Click event. The EventArgs Object Literal has the following definition:

var EventArgs = {
   CommandName: _CommandName, // Base Command name of the Item.
   Text: _Text, // Item Text.
   IsDisabled: _IsDisabled, // Indicate whether Item to be disabled or not.
   ImageUrl: _ImageUrl // Path of the Item image. 
};

Note that the Click event handler is a C# style event handler.

Using the Control

Add a reference to the ContextMenu.js file in your web page, as:

<script type="text/javascript" src="JS/ContextMenu.js"></script>

Create a div element on the web page, as:

<div id="div" style="width: 925px; height: 300px; background-color: silver;">
</div>

Now, create a script tag in the head section of the web page and add the following code in the window.onload event:

<script type="text/javascript">
    var oCustomContextMenu = null;
    var oBase = null;
    
    window.onload = function()
    {
        oBase = document.getElementById('div');
        
        var Arguments = {
            Base: oBase,
            Width: 200,
            FontColor: null,
            HoverFontColor: null,
            HoverBackgroundColor: null,
            HoverBorderColor: null,
            ClickEventListener: OnClick
        };
        
        oCustomContextMenu = new CustomContextMenu(Arguments); 
                        
        oCustomContextMenu.AddItem('Images/ei0019-48.gif', 'Add', false, 'Add');
        oCustomContextMenu.AddItem('Images/save.png', 'Save', true, 'Save');
        oCustomContextMenu.AddSeparatorItem();
        oCustomContextMenu.AddItem('Images/ei0020-48.gif', 'Update', false, 'Update');
        oCustomContextMenu.AddSeparatorItem();
        oCustomContextMenu.AddItem(null, 'Cancel', false, 'Cancel');
    } 
</script>

First, get the reference of the Base object and create an Arguments Object Literal with the necessary properties. After that, instantiate a context menu object using the new keyword and add the context menu items. Don’t forget the Click event wire up in the Arguments Object Literal:

ClickEventListener: OnClick 

Now, create a Click event handler as a local anonymous method:

var OnClick = function(Sender, EventArgs)
{
    //Code
    …
    oCustomContextMenu.Hide();
} 

//Example:

var OnClick = function(Sender, EventArgs)
{
    switch(EventArgs.CommandName)
    {
        case 'Add':
            alert('Text: ' + EventArgs.Text);
            alert('IsDisabled: ' + EventArgs.IsDisabled);
            alert('ImageUrl: ' + EventArgs.ImageUrl);
            break;
        case 'Save':
            alert('Text: ' + EventArgs.Text);
            alert('IsDisabled: ' + EventArgs.IsDisabled);
            alert('ImageUrl: ' + EventArgs.ImageUrl);
            break;
        case 'Update':
            alert('Text: ' + EventArgs.Text);
            alert('IsDisabled: ' + EventArgs.IsDisabled);
            alert('ImageUrl: ' + EventArgs.ImageUrl);
            break;
        case 'Cancel':
           alert('Text: ' + EventArgs.Text);
           alert('IsDisabled: ' + EventArgs.IsDisabled);
           alert('ImageUrl: ' + EventArgs.ImageUrl);
           break;
    }
    
    oCustomContextMenu.Hide();
}

This method will get called when you click on any item of the context menu. Don’t forget to invoke the Hide method at last in the event handler.

Now, attach the oncontextmenu event on the div that has been created earlier:

<  oncontextmenu="javascript:return oCustomContextMenu.Display(event);"  >

Invoke the Dispose method in the window.onunload event in order to destroy the context menu object:

window.onunload = function(){ oCustomContextMenu.Dispose(); }

Conclusion

So this is my approach. I was working for a long time to create C# like event handlers for JavaScript classes and finally, I’ve done it. Please let me know of any bugs and suggestions to improve this context menu control.

Browser Compatibility

I have tested this control on various browsers and it works fine except on Opera as Opera doesn’t support the oncontextmenu event. If any one has information regarding simulating the oncontextmenu event on Opera, kindly let me know. The following are the supported browsers:

Browsers.png

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Samir NIGAM
Team Leader
India India
Member
SAMIR NIGAM is a CodeProject MVP, a Microsoft Certified Technology
Specialist (MCTS)
as well as a Microsoft Certified Professional Developer (MCPD)
in C# for web-based applications. He is an insightful IT professional with
results-driven comprehensive technical skill having rich, hands-on work experience
in web-based applications using ASP.NET, C#, AJAX, Microsoft
Enterprise Library
, MS SQL Server 2005.
He has earned his master degree (MCA) from U.P. Technical University, Lucknow,
INDIA, his post graduate dipoma (PGDCA ) from Institute of Engineering and
Rural Technology, Allahabad, INDIA and his bachelor degree (BSc - Mathematics)
from University of Allahabad, Allahabad, INDIA.
He has good knowledge of Object Oriented Programming, 3-Tier Architecture
and Algorithm Analysis & Design as well as good command over cross-browser
client side programming using JavaScript.
Awards:


Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questiontext of a linkbutton on which rightclick is made Pinmemberanjalisushma27 Mar '13 - 23:28 
QuestionContext Menu Pinmemberanjalisushma15 Mar '13 - 3:15 
QuestionThank U, one question here Pinmemberbhaskarsgb5 Nov '12 - 19:37 
GeneralMy vote of 5 PinmemberPrasyee2 Oct '12 - 23:49 
Questionnot working..please HELP!! Pinmembertripti69017 Sep '12 - 1:54 
Questioncomment Pinmembershilpi cgi31 Jul '12 - 21:26 
QuestionHAi Pinmemberlij thomas23 Nov '11 - 19:22 
BugNot working on IE8 / Compatibility View Pinmember_skidrow_vn_22 Aug '11 - 6:59 
QuestionMy vote of 6 Pinmember_skidrow_vn_21 Aug '11 - 22:10 
QuestionHow to add Multlevel Pinmemberkeyur soni25 Jul '11 - 21:59 
GeneralMy vote of 5 Pinmemberjasv25 May '11 - 6:15 
QuestionDisplay many context menu PinmemberMember 29335001 May '11 - 23:38 
QuestionNot able to get Exact Sender when context Menu is opened? PinmemberShailendra_atrey14 Nov '10 - 23:33 
GeneralEnable a Disabled Menu [modified] PinmemberSatish Panchware6 Jan '10 - 2:53 
GeneralFIREFOX functionality and POPUPMENU location FIX PinmembercjsmithMRC14 Jul '09 - 15:40 
GeneralGreat PinmemberRajeesh MP8 Apr '09 - 2:20 
QuestionWhen Sub Menu support ??? PinmemberJLKEngine0083 Apr '09 - 17:10 
GeneralUrgent!! Urgent!! Urgent!! Pinmembermohd rabi11 Feb '09 - 15:27 
Questionwhen support Sub Menu ??????? PinmemberJLKEngine00817 Sep '08 - 18:31 
Questionadd onclick to menu items? Pinmemberian_smith3316 Sep '08 - 23:00 
Generalerror Pinmemberaj_1429 Aug '08 - 11:03 
QuestionWhen Sub Menu support in the next update??? PinmemberJLKEngine00828 Aug '08 - 22:34 
QuestionEXCELLENT ARTICLE, hav a doubt, could u pl help...... Pinmemberitc12323 Aug '08 - 19:11 
GeneralDoesn't work in FF (unless you alter the about:config settings) Pinmemberatorreano16 Jul '08 - 12:25 
GeneralExcellent work PinmemberMember 32062504 Jul '08 - 19:01 
QuestionSub Menu Support? PinmemberDan Avni30 Jun '08 - 20:38 
Questionnice work! Pinmemberwuxsh29 Jun '08 - 22:40 
GeneralNice article and good work PinmemberMember 381396218 Jun '08 - 5:49 
Generalhandy stuff PinmemberRajib Ahmed17 Jun '08 - 5:23 
Generalhi Pinmembercrazsmith17 Jun '08 - 5:12 
GeneralGreat tool - minor typo. Pinmemberdpminusa17 Jun '08 - 2:22 
GeneralSlowly expanding of panel PinmemberS_Aijaz116 Jun '08 - 17:57 
GeneralXcelent PinmemberAbhijit Jana12 Jun '08 - 5:36 
GeneralNice one !!! Pinmemberdnpro9 Jun '08 - 22:26 
Generalhmm... Pinmember4866030_us9 Jun '08 - 18:27 
Generalhi Pinmembergood.morning_everyday9 Jun '08 - 18:25 
Generalgood Pinmembersteve_19709 Jun '08 - 18:22 
GeneralGreat Job PinmemberJHON HOVE9 Jun '08 - 18:20 
GeneralNice ! Pinmemberholy_spirit9 Jun '08 - 3:57 
GeneralSir Very Nice Work PinmemberSandeep Shekhar9 Jun '08 - 2:39 
GeneralGood Work PinmemberMCSDvikasmisra9 Jun '08 - 1:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 24 Jun 2008
Article Copyright 2008 by Samir NIGAM
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid