Question

I want to handle right click event on a particular div element. After digging through a number of answers in stackoverflow, I came up with this:

 $('#mydiv').mousedown(function(event) {
if ((event.which == 3)&& (event.target.nodeName == 'SPAN')){
     $("#outpdiv").append($(event.target).text().concat(" , "));
     event.preventDefault();
}
 });

As you can see, I am trying to to append the content of span elements inside mydiv to another div element outpdiv. This works fine, but the problem is after right click, the contextmenu is shown. Apparently, event.preventDefault() does not work. How can I get around this problem so that the context menu is not shown after you do the right click?

Was it helpful?

Solution

Try capturing the contextmenu event and calling preventDefault() in that handler:

http://jsfiddle.net/cTp9x/

$('#mydiv').mousedown(function (event) {
    if ((event.which == 3) && (event.target.nodeName == 'SPAN')) {
        $("#outpdiv").append($(event.target).text().concat(" , "));        
    }
});

$(document).on('contextmenu', function(e) {
    e.preventDefault();
});

In response to your comment. If you only want to disable the context menu when you click that particular div, you can bind the handler to it. Switching between jQuery and native event handlers is messy, IMO:

$('#mydiv').on('contextmenu', function(e) {
    e.preventDefault();
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top