Web Development

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!

About the author

Written by .

If you found this post useful you may also want to check these out:

  1. Customized Right Click Menu in Flash MX 2004
  2. Finding the Length of a String in JavaScript
  3. Client-side Validation with Javascript
  4. Enumerating JavaScript Objects
  5. How to Hide your JavaScript with PHP!
  6. Dropdown Menu in Flash MX 2004
  • Problem

    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..