Helping ordinary people create extraordinary websites!
HOME TUTORIALS SCRIPTS WEB HOSTING BLOG FORUM
Get Our Newsletter
Your Email:
Webmaster Blog

Designing Context menu in Javascript

by Hasin Hayder


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!




Related Posts
» Designing and Coding a Wordpress Theme From Scratch (Part 7)
» Designing and Coding a Wordpress Theme From Scratch (Part 9)
» Coding Javascript, but longing for PHP?
» Designing and Coding a Wordpress Theme From Scratch (Part 5)
» Designing and Coding a Wordpress Theme From Scratch (Part 8)
 


This post has One Response so far.
  1. Problem Says:
    October 20th, 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 Reply

Ask A Question
characters left.