5,693,062 members and growing! (16,894 online)
Email Password   helpLost your password?
Web Development » Client side scripting » Controls     Intermediate License: The Code Project Open License (CPOL)

JavaScript Context Menu Control

By Sameer NIGAM

Cross-browser JavaScript context menu control for web applications.
C# (C# 2.0, C#), Javascript, CSS, HTML, XHTML, .NET (.NET, .NET 2.0), ASP, ASP.NET, WebForms, Ajax, Dev

Posted: 9 Jun 2008
Updated: 23 Jun 2008
Views: 20,809
Bookmarked: 67 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
32 votes for this Article.
Popularity: 6.80 Rating: 4.52 out of 5
1 vote, 3.1%
1
1 vote, 3.1%
2
2 votes, 6.3%
3
2 votes, 6.3%
4
26 votes, 81.3%
5

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

Sameer NIGAM


Currently I'm working as a Sr. Software Engineer in SRM Techsol Pvt. Ltd., Lucknow, INDIA. I possess following degrees:

  • MCA from U.P. Technical University, Lucknow, INDIA.
  • PGDCA from Institute of Engineering and Rural Technology, Allahabad, INDIA.
  • BSc from University of Allahabad, Allahabad, INDIA.


Award: Best ASP.NET article of June 2008: JavaScript ListBox Control

Occupation: Software Developer (Senior)
Company: STPL
Location: India India

Other popular Client side scripting articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 41 (Total in Forum: 41) (Refresh)FirstPrevNext
Generalwhen support Sub Menu ???????memberJLKEngine00819:31 17 Sep '08  
Questionadd onclick to menu items?memberian_smith330:00 17 Sep '08  
Generalerrormemberaj_1412:03 29 Aug '08  
GeneralRe: errormemberSAMir Nigam0:12 30 Aug '08  
GeneralWhen Sub Menu support in the next update???memberJLKEngine00823:34 28 Aug '08  
QuestionEXCELLENT ARTICLE, hav a doubt, could u pl help......memberitc12320:11 23 Aug '08  
AnswerRe: EXCELLENT ARTICLE, hav a doubt, could u pl help......memberSAMir Nigam20:19 24 Aug '08  
GeneralDoesn't work in FF (unless you alter the about:config settings)memberatorreano13:25 16 Jul '08  
GeneralExcellent workmemberMember 320625020:01 4 Jul '08  
GeneralRe: Excellent workmemberSAMir Nigam21:16 4 Jul '08  
GeneralSub Menu Support?memberDan Avni21:38 30 Jun '08  
GeneralRe: Sub Menu Support?memberSAMir Nigam21:14 4 Jul '08  
Questionnice work!memberwuxsh23:40 29 Jun '08  
AnswerRe: nice work!memberSAMir Nigam19:56 30 Jun '08  
GeneralNice article and good workmemberMember 38139626:49 18 Jun '08  
GeneralRe: Nice article and good workmemberSAMir Nigam19:02 18 Jun '08  
Generalhandy stuffmemberRajib Ahmed6:23 17 Jun '08  
GeneralRe: handy stuffmemberSAMir Nigam19:04 18 Jun '08  
Generalhimembercrazsmith6:12 17 Jun '08  
GeneralRe: himemberSAMir Nigam19:05 18 Jun '08  
GeneralGreat tool - minor typo.memberdpminusa3:22 17 Jun '08  
GeneralRe: Great tool - minor typo.memberSAMir Nigam19:06 18 Jun '08  
GeneralSlowly expanding of panelmemberS_Aijaz118:57 16 Jun '08  
GeneralXcelentmemberAbhijit Jana6:36 12 Jun '08  
GeneralRe: Xcelentmember SAMir Nigam 19:14 12 Jun '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 23 Jun 2008
Editor: Chris Maunder
Copyright 2008 by Sameer NIGAM
Everything else Copyright © CodeProject, 1999-2008
Web17 | Advertise on the Code Project