///Designing Context menu in Javascript

Designing Context menu in Javascript

Context menu pops up when you right click over any object. Every web browsers display default context menu when you right click on any object inside it. And context menus are different based on the type of object. For example you will not get same menu when you click on a text area and other contents. In this blog post we will show you how you can override the default context menu and design your own using jQuery and a tiny plugin called “contextmenu” plugin. This plugin is very small in size, weighs only 2.5KB when compressed. Lets have a look at the following code to understand how to use it.

Design your context menu

  <div class="contextMenu" id="menu">
    <ul>
      <li id="item_1">Item 1</li>
      <li id="item_2">Item 2</li>
      <li id="item_3">Item 3</li>
    </ul>
  </div>

Download the plugin script and load it
You can download the plugin from here and load the script like shown below. You must load jQuery to make it work.
<script type=’text/javascript’ src=’jquery.js’></script>
<script type=’text/javascript’ src=’contextmenu.js’></script>

Plug the menu with a textarea
Now we will plug in that context menu with a text area object, overriding the default one.

<textarea id='sampleTA' ></textarea>
<script>
    $('#sampleTA').contextMenu('menu', {
    	menuStyle: {
    		width: '150px'
    	},
    	bindings: {
    	'item_1': function(t) {
    		alert('You choose item 1');
    	},
    	'item_2': function(t) {
    		alert('you choose item 2');
    	},
    	'item_3': function(t) {
    		alert('you choose item3');
    	}
    	}
    });
</script>

Now if you run the example above you will see something like this
Context Menu

Thats it!

2010-05-19T23:02:29+00:00 March 5th, 2008|JavaScript|1 Comment

About the Author:

One Comment

  1. Problem October 20, 2008 at 2:27 AM

    Sir,

    I need your code to implement a context menu in my home page.
    I saved your context menu plug-in as jquery.js and i do not know which file is to save as contextmenu.js.

    Next, i copied the code …and the following script in my home page.But, it will display the three items and textarea in home page.
    There is no context menu display. Help me..

Leave A Comment