Fork me on GitHub

Utility plugins

contextMenu.js is a plugin to create windows like context menu with keyboard ineteraction, different type of inputs ,trigger events and much more.
Why contextMenu.js ?:

  • Use as simple popup or as a context menu. With some twick can be used for multi purpose.
  • Adjust position and size to fit in viewport.
  • Keyboard interaction.
  • Support different type of inputs (json, UL list)  .
  • Trigger Context menu with right-click, left-click,hover or any other mouse events.
  • Css outside of javascript so you can edit the look of menu.
  • Enable/disable options.
  • Optional icons for commands.
  • Lot of configurable options.
  • Submenus
Download

Examples

Simple context menu

Click me

//For example we are defining menu in JSON format. You can also define it on Ul list. See on documentation.
var menu = [{
  	    name: 'create',
  	    img: 'images/create.png',
  	    title: 'create button',
  	    fun: function () {
  	        alert('i am add button')
  	    }
  	}, {
  	    name: 'update',
  	    img: 'images/update.png',
  	    title: 'update button',
  	    fun: function () {
  	        alert('i am update button')
  	    }
  	}, {
  	    name: 'delete',
  	    img: 'images/delete.png',
  	    title: 'create button',
  	    fun: function () {
  	        alert('i am add button')
  	    }
  	}];

//Calling context menu
 $('.testButton').contextMenu(menu);


Popup menu

Click me
Popup menu are used to display content around the cursor or trigger button.
This are much dependent on defined styles and interaction.

Close menu

$('.testButton').contextMenu('#popupMenu');

Enable/disable menu options

Click me
  

var menu = [{
    name: 'create',
    img: 'images/create.png',
    title: 'create button',
    disable: 'true',
    fun: function () {
        alert('i am add button')
    }
}, {
    name: 'update',
    img: 'images/update.png',
    title: 'update button',
    subMenu: [{
        name: 'merge',
        title: 'It will merge row',
        img: 'images/merge.png',
        fun: function () {
            alert('It will merge row')
        }
    }, {
        name: 'replace',
        title: 'It will replace row',
        img: 'images/replace.png',
        disable: 'true',
        subMenu: [{
            name: 'replace top 100',
            img: 'images/top.png',
            fun: function () {
                alert('It will replace top 100 rows');
            }

        }, {
            name: 'replace all',
            img: 'images/all.png',
            fun: function () {
                alert('It will replace all rows');
            }
        }]
    }]
}, {
    name: 'delete',
    img: 'images/delete.png',
    title: 'create button',
    subMenu: [{
        'name': 'soft delete',
        img: 'images/soft_delete.png',
        fun: function () {
            alert('You can recover back');
        }
    }, {
        'name': 'hard delete',
        img: 'images/hard_delete.png',
        fun: function () {
            alert('It will delete permanently');
        }
    }]

}];

//Calling context menu
$('.testButton').contextMenu(menu);

//Enable option
$('#enableOption').click(function (e) {
    var updateJson = [{
        name: 'create',
        disable: 'false',
    }, {
        name: 'update',
        subMenu: [{
            name: 'replace',
            disable: 'false',
        }]
    }];
    $('.testButton').contextMenu('update', updateJson);

});

//disable option
$('#disableOption').click(function (e) {
    var updateJson = [{
        name: 'create',
        disable: 'true',
    }, {
        name: 'update',
        subMenu: [{
            name: 'replace',
            disable: 'true',
        }]
    }];
    $('.testButton').contextMenu('update', updateJson);

});

** Note ** If input type is ul list just add/remove iw-mDisable in your menu options and do a update to contextMenu

 $('.testButton').contextMenu('update');
 

Overriding browser context menu


//Calling context menu
$('body').contextMenu(menu,{triggerOn:'contextmenu'});

Context menu as validation tip box

Name
:
  • Special character not allowed
User name
:
  • Minimum six characters
Password
:
  • Minimum six characters
  • Must contain any number
  • Must contain any special character


$('.validate').each(function () {
    elm = $(this);
    elm.contextMenu(elm.siblings('.valTip'), {
        'triggerOn': 'focusin',
        'displayAround': 'trigger'
    });

});
$('.validate').focusout(function (e) {
    $(this).siblings('.valTip').css('display', 'none');
});

Context menu as simple model box


var modalSetting={
	top:'50%',
	left:'50%',
	afterOpen:function(data,e){
		var menu=data.menu,
			menuWidth=menu.innerWidth(),
			menuHeight=menu.innerHeight();
			
			menu.css({
				'margin-left':-(menuWidth/2)+'px',
				'margin-top':-(menuHeight/2)+'px'
				});
			
			$('#overlayDiv').show();	
		},
	onClose:function(data,e){
		var menu=data.menu;			
			menu.css({
				'margin-left':'',
				'margin-top':''
				});
			
			$('#overlayDiv').hide();			
		}	
};
$('#openModal').contextMenu('#modalBox',modalSetting);

Context menu as simple tool tip

Hover me to see tooltip


$('div,span,img,a').filter(function () {
    return this.title != '';
}).each(function (index, element) {
    var title = this.title,
        titleId = parseInt(Math.random() * 100000),
        tiltleDiv = $('<div class="titleDiv" style="display:none" titleId="' + titleId + '">' + title + '</div>');

    $('#tipContainer').append(tiltleDiv);
    $(this).attr({
        'title': '',
        'original-title': title,
        'titleId': titleId
    }).contextMenu(tiltleDiv, {
        triggerOn: 'hover',
        displayAround: 'trigger',
        sizeStyle: 'content',
        position: 'bottom'
    });
});

Context menu as simple menu

Navigation menu
See it on right side navigation menu.

$('#pageNav').find('li').each(function (index, element) {
    var elm = $(this),
        subNav = elm.attr('subNav');

    if (subNav && (subNav != '')) {
        elm.contextMenu('menu', '#' + subNav, {
            triggerOn: 'hover',
            displayAround: 'trigger',
            position: 'right',
            verAdjust: -40
        })
    }
});


An other example

var menuTrgr=$('#menuTrigger');
menuTrgr.contextMenu('menu','#demoMenu',{
	displayAround:'trigger',
	horAdjust:-menuTrgr.width()
	})



Test all options

Trigger on Dispaly Around
Mouse click sizeStyle
Vertical adjust Horizontal Adjust
Top Left
Containment Force position
     

Documentation

Options

Option Default Allowed Description
triggerOn click click,hover, mousemove, dblclick and all mouse events Event in which context menu is binded with a trigger.
displayAround cursor cursor , trigger (button) Display context menu around cursor position or trigger position
mouseClick left left,right which mouse button to trigger context menu if trigger event is mouse click or mouse up event.
verAdjust 0 Numeric value Adjusting the vertical distance from its original pixel.
horAdjust 0 Numeric value Adjusting the horizontal distance from its original pixel.
top auto auto,top position in px or % Defines the exact top position relative to the containment where menu to be shown.
left auto auto,top position in px or % Defines the exact left position relative to the containment where menu to be shown.
containment window window, any selector,jquery object, document object Define the container inside which context menu will be contained.
winEventClose true true,false If true close the context menu on window scroll and resize event.
closeOther true true,false If true close already opened contextMenu (Maintaining one instance a time).
sizeStyle auto auto, content If auto, size of context menu depends on browser size and options you selected. If content size depends on content width and height.
position auto auto,left,right,top,bottom Context menu adjust according to viewport. If other than auto is given it ill force contenxt menu to be on that position. It is considered only when displayAround is set to trigger.


Callback

Callback Description
onOpen This is called just before context menu opens.
afterOpen This is called after context menu opens.
onClose This is called just after context menu is closed.
Callback accept two argument.
1. data : Which containg refrence to trigger and menu.
You can get trigger and menu using data.trigger and data.menu.
2. event : A event object which is binded with trigger to open context menu.

Inside callback this refers to trigger element.

Method

Method Description
menu This mode is used to show context menu. Keyboard interaction and sub menus are activated in this mode.
popup If you just want to display an popup window at your trigger point popup mode serve best. This will just show element defined in selector while adjusting it according to view port.
update This mode is used to update the menu items (like enabling, disabling, icon change and function) and configuration option.
refresh If new trigger with specific selector is added, this method is used to initialize context menu on those newly added elements.
destroy Remove context menu instance for that trigger completely.
close To manually close context menu.
Popup method is default when selector type is selector string , jquery object, DOM object. Menu method is default when selector type is JSON object. Context menu accept three parameters.

$('.trigger).contextMenu(method,selector,options)
1. method tells what operation to trigger . By default it is popup if selector is string type (selector notation) and menu if selector is json object.
2. selector can be document object , jQuery object ,selector string or JSON object.
3. option, there are different options to change the behaviour of context menu. This parameter is optional where all options contain some default value. .

Input format

If defined in menu mode you can provide input in two way.
1. By passing selector of ul list.
2. By passing a JSON containg menu defination.

1. UL List format

<ul class="contextMenu">
    <li title="create button" onclick="doCreate()">
        <img src="images/create.png" class="iw-mIcon" />Create</li>
    <li title="update button" onclick="doUpdate()">
        <img src="images/update.png" class="iw-mIcon" />Update
        <ul>
            <li onclick="doMerge()">Merge</li>
            <li>Replace
                <ul>
                    <li>Replace Top 100</li>
                    <li>Replace All</li>
                </ul>
            </li>
        </ul>
    </li>
    <li onclick="doDelete()">
        <img src="images/delete.png" class="iw-mIcon" />Delete
        <ul>
            <li>Soft Delete</li>
            <li>Hard Delete</li>
        </ul>
    </li>
    <li class="iw-mDisable">Disabled</li>
</ul>
  
**Note**
1. To disable any option add "iw-mDisable" class in the option.
2. Submenu are ul list inside a option li.
3. Option icon have class "iw-mIcon".

JSON object format

  	var menu = [{
  	    name: 'create',
  	    img: 'images/create.png',
  	    title: 'create button',
  	    fun: function () {
  	        say('i am add button')
  	    }
  	}, {
  	    name: 'update',
  	    img: 'images/update.png',
  	    title: 'update button',
  	    fun: function () {
  	        say('i am update button')
  	    },
  	    subMenu: [{
  	        name: 'merge',
  	        title: 'It will merge row',
  	        fun: function () {
  	            say('It will merge row')
  	        }
  	    }, {
  	        name: 'replace',
  	        subMenu: [{
  	            name: 'replace top 100'
  	        }, {
  	            name: 'replace all'
  	        }]
  	    }]
  	}, {
  	    name: 'delete',
  	    img: 'images/create.png',
        disable:true,
  	    title: 'create button',
  	    fun: function () {
  	        say('i am add button')
  	    },
  	    submenu: [{
  	        'name': 'soft delete',
  	    }, {
  	        'name': 'hard delete'
  	    }]

  	}];
  
Keys :
1. name : name of the option.
2. img :option icon image.
3. title : tiltes for the options.
4. disable : A boolean to tell weather that option is disabled or not. If true option is disabled.
5. fun :Function that will be executed on click of option.
6. submenu : A submenu defination which has all options available as we are giving for parent menu. Submenus can bgo to any level.

Key board interaction.

Key Operation
Up arrow Go to previous option in menu.
Down arrow Go to next option in menu.
Left arrow Go to parent menu.
Right arrow Go to sub(child) menu.
Page up Go to first option.
Page down Go to last option.
Esc key Close context menu.
Enter Key Trigger the function associated with option.

Closing of menu

Menus are closed in following actions of user.
1. On esc key press.
2. On clicking outside of window.
3. Window scroll or resize events(If winEventClose not set to false).

Updating menu


A menu configuration options and image icon, disabling, title and function can be changed dynamically. If you want to change the structure, you need to destroy menu and create again.
You also can't change the option name, as it its part of structure. To update a menu you can pass update json and configuration option.

Update JSON is similiar to input JSON but in this you need to only pass those key which you want to update. Ex.

var updateJson = [{
    name: 'create',
    disable: 'true',
}, {
    name: 'update',
    subMenu: [{
        name: 'replace',
        disable: 'true',
    }]
}];

$('.trigger').contextMenu('update', updateJson, {
    'displayAround': 'trigger',
    'containment': '#contaienr'
});

You can also directly change on html dom.
If you know the selector of menu its great or else you can get menu object by.
 var menu=$('.trigger').contextMenu('value','menu'); 

Now you can update it however you want.After that call update method( with configuration option, if you want to change it).

$('.trigger').contextMenu('update',updateJson,{
    'displayAround':'trigger',
    'containment':'#container'
});
For enabling/disabling a menu option just add "iw-mDisable" class if you are changing in html dom.
Else if you are updating using update json add disable key with value of true(to disable) or false(to enable) in json.

Refreshing trigger list

If you working on dynamic content you may require to add newly added element in trigger list.
You can refresh the trigger list using
$('.trigger').contextMenu('refresh');
Note : Refresh method work only when contextMenu is already initialized to any one of element which belongs to that selector.

Destroying a context menu

This method will destroy context menu binded with trigger element. To call destroy method.
$('.trigger').contextMenu('destroy');

Getting values associated with context menu.

value method return value associated with key passed as second argument.
ex :
$('.trigger').contextMenu('value',key);
Here key are 'menu','menuId' and any configuration options.

CSS Class

Following classes are associated with context menu.
Class Description
iw-contextMenu All context menu get this class on initializing context menu
iw-cm-menu This class is added on those which are activated in menu mode.
iw-mOverlay This class is applied on overlay which come inside menu option when we disable that option
iw-mDisable This class is added on menu options which are disabled.
iw-mSelected This class is added on menu option which is currently focused.
iw-cm-arrow-right If any menu option have submenu a arrow sign is added with this class to show it has submenu.
iw-mTrigger This class is added on all triggers and also on menu option which have submenus.
iw-mIcon This class is added on icon images used for menu options.

Concept

This documentaion is moved to http://ignitersworld.com/lab/contextMenu.html. It will be no longer maintained here .