Create a right click menu for your web application
Taken out of context I must seem so strange.
-Ani DiFranco
Update: I ve converted this into a jquery plugin. You can download/fork it from my gitbhub page.
There is a common issue when crafting out non-trivial web applications, where you may have many different actions for the user to perform and yet you certainly do not want to overwhelm her with a complex UI with icons, menus, floating divs with action buttons in them etc. A simpler way to reduce the UI clutter could be to introduce a contextual menu on right-clicking an element. This is really simple using jQuery. Here s a DEMO for the following snippet. And here’s the demo for the same thing as a jquery plugin.
You could design a UL element the way you want and set
ul#context-menu {
postion: absolute;
display: none;
/*sample style attributes follow*/
width: 100px;
background: #333;
color: #fff;
font-size: 12px;
}
ul#context-menu li {
margin: 3px;
padding: 3px;
background: #000;
}
Assuming that we want this context menu to appear on right clicking an image, the sample HTML could be:
<img src='' /> <ul id='context-menu'> <li>Edit</li> <li>Delete></li> <li>Export</li> </ul>
Now we simply bind the ‘contextmenu’ event of images to show this context menu.
$('img').bind('contextmenu', function(e){
$('#context-menu').css('left', e.pageX + 'px');
$('#context-menu').css('top', e.pageY + 'px');
$('#context-menu').show();
e.preventDefault();
return false;
});
Basically, we got the X and Y position of the current mouse position and applied it to the context-menu UL element (which has position set to absolute) and prevented the default action from happening. Finally, we need to get rid of this context menu if the user clicks anywhere but the context menu.
$('html').click(function(e){
$('#context-menu').hide();
});
We don’t want the menu to hide if the user clicked the menu itself, so we disable the default behavior of the element from propagating the click event way up to the HTML element:
$('#context-menu').click(function(e){
e.stopPropagation();
});
Since we set position: absolute on the context menu, resizing the browser when its open will mess it s position. The probability of the user right clicking the image and then resizing the browser window is low, but just in case she does so, then we can simply hide the menu on resize as well:
$(window).resize(function() {
$('#context-menu').hide();
});
So that s about it. Here’s a DEMO for this code. If you d like to see a demo of this same thing used as a jQuery plugin, then here’s the link for that and finally, here s my github page for it.


Pingback: Create a right click menu for your web application | Walmik's weblog | Add My Site Web Development News