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.

RIGHT CLICK HERE

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.

RIGHT CLICK HERE

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.

Comments