Modify right-click menu behavior with jQuery
Posted December 11th, 2009 in Javascript
This post shows how to modify the right-click menu with jQuery - it's possible to either completely disable right-click context senstive menus or replace them with a custom dialog which is applicable to the application. This can be done to the page as a whole or just a specific element. While it's not normally a good idea to remove or change the right-click menu, sometimes it makes sense for a specific application.
Working Examples
The following <div> disables right-clicking. If you right click elsewhere on the page the context sensitive menu will appear. If you right click the <div> below it will not. Note that this will not work if you are reading this in a feed reader. Click through to view this article in a web browser.
The second example below shows a custom "menu" which appears when right-clicking instead of the default context sensitive menu. Click it or anywhere on the page to get rid of it.
How to disable the right click menu
To disable the right click menu with jQuery for the page as a whole do this:
$(document).bind("contextmenu", function(e) {
return false;
});
To do it for just a particular element do this:
$("#myid").bind("contextmenu", function(e) {
return false;
});
To show a custom menu instead
The second example above uses a "menu" defined with the following CSS:
#menu {
display: none;
position: absolute;
padding: 10px;
background-color: #ddd;
border: 1px solid #000;
}
Note that it is hidden with display: none and positioned absolutely. These are the only two required styles and for the rest it's up to you to pretty up.
Then bind the menu appearing at the mouse co-ordinates on right-click:
$(document).bind("contextmenu", function(e) {
$('#menu').css({
top: e.pageY+'px',
left: e.pageX+'px'
}).show();
return false;
});
And then add a handler for closing the menu when the page is clicked or the menu clicked:
$(document).ready(function() {
$('#menu').click(function() {
$('#menu').hide();
});
$(document).click(function() {
$('#menu').hide();
});
});
The $('#menu').click could alternatively be handled by the <a> tags in the menu.
Related posts:
- Get the mouse co-ordinates with jQuery when an element is clicked (Friday, October 9th 2009)
- Get the mouse co-ordinates with jQuery (Tuesday, October 6th 2009)
- How to tell if an element is visible with jQuery (Friday, September 18th 2009)
- Calling $(document).ready multiple times with jQuery (Friday, September 11th 2009)
- Relatively moving a div left or right with jQuery (Friday, August 28th 2009)

Comments
blog comments powered by Disqus