Jquery/JS prevent right click menu in browsers

JavascriptJqueryRight Click

Javascript Problem Overview


I have my div with a right click popup menu:

// Attatch right click event to folder for extra options
$('#fBox' + folderID).mousedown(function(event) {
    if (event.which == 3) {

        // Set ID
        currRClickFolder = folderID;

        // Calculate position to show popup menu
        var height = $('#folderRClickMenu').height();
        var width = $('#folderRClickMenu').width();
        leftVal = event.pageX - (width / 2) + "px";
        topVal = event.pageY - (height) + "px";
        $('#folderRClickMenu').css({ left: leftVal, top: topVal }).show();

    }
});

But the browser for this element still pops up the default menu (copy/paste/properties etc). Any way to disable this? I've tried return false but not luck.

Javascript Solutions


Solution 1 - Javascript

You can disable the right click by appending oncontextmenu="return false;" to your body tag.

<body oncontextmenu="return false;">

Solution 2 - Javascript

You can disable context menu on any element you want:

$('selector').contextmenu(function() {
	return false;
});

To disable context menu on the page completely (thanks to Ismail), use the following:

$(document).contextmenu(function() {
	return false;
});

Solution 3 - Javascript

One jQuery line:

$('[id^="fBox"]').on("contextmenu", function(evt) {evt.preventDefault();});

Solution 4 - Javascript

Try this:

$('#fBox' + folderID).bind("contextmenu", function () {
                alert("Right click not allowed");
                return false;
            });

Solution 5 - Javascript

Try...

$('[id^="fBox"]').mousedown(function(event) {
    if (event.which == 3) {
        event.preventDefault();
        // Set ID
        currRClickFolder = $(this).attr('id').replace('fBox','');

        // Calculate position to show popup menu
        var height = $('#folderRClickMenu').height();
        var width = $('#folderRClickMenu').width();
        leftVal = event.pageX - (width / 2) + "px";
        topVal = event.pageY - (height) + "px";
        $('#folderRClickMenu').css({ left: leftVal, top: topVal }).show();

    }
});

if you have any dynamic creation of these boxes then...

$('[id^="fBox"]').live('mousedown',function(event) {
    ...
});

Solution 6 - Javascript

I agree with @aruseni, blocking oncontextmenu at the body level you'll avoid the standard context menu on the right click for every element in the page.

But what if you want to have a finer control?

I had a similar issue and I thought I've found a good solution: why not attaching directly your context menu code to the contextmenu event of the specific element(s) you want to deal with? Something like this:

// Attatch right click event to folder for extra options
$('#fBox' + folderID).on("contextmenu", function(event) {
  // <-- here you handle your custom context menu
  // Set ID
  currRClickFolder = folderID;
  
  // Calculate position to show popup menu
  var height = $('#folderRClickMenu').height();
  var width = $('#folderRClickMenu').width();
  leftVal = event.pageX - (width / 2) + "px";
  topVal = event.pageY - (height) + "px";
  $('#folderRClickMenu').css({ left: leftVal, top: topVal }).show();
	
  event.stopImmediatePropagation();
  return false; // <-- here you avoid the default context menu
});

Thus you avoid handling two different events just to capture the context menu and customize it :)

Of course this assumes you don't mind having the standard context menu displayed when someone clicks the elements you didn't select. You might as well show different context menus depending on where users right-click..

HTH

Solution 7 - Javascript

This is a default behavior of browsers now to disable the alternate-click override. Each user has to allow this behavior in recent browsers. For instance, I don't allow this behavior as I always want my default pop-up menu.

Solution 8 - Javascript

Using jQuery:

$('[id^="fBox"]').bind("contextmenu",function(e){
    return false;
});

Or disable context menu on the whole page:

$(document).bind("contextmenu",function(e){
    return false;
});

Solution 9 - Javascript

For me

$('body').on('contextmenu',function(){return false;});

jQuery does the job :)

Solution 10 - Javascript

// Attatch right click event to folder for extra options
$('#fBox' + folderID).mousedown(function(event) {
    if (event.which == 3) {
        event.preventDefault();
        // Set ID
        currRClickFolder = folderID;

        // Calculate position to show popup menu
        var height = $('#folderRClickMenu').height();
        var width = $('#folderRClickMenu').width();
        leftVal = event.pageX - (width / 2) + "px";
        topVal = event.pageY - (height) + "px";
        $('#folderRClickMenu').css({ left: leftVal, top: topVal }).show();

    }
});

Solution 11 - Javascript

Here's a way I used recently (using a little jQuery too,) when I was running into a problem with it. Since the mousedown event occurs before the contextmenu, this trick seems to catch it, which is attaching a body level oncontextmenu handler to return false temporarily in the mousedown event, perform your desired action, then as an important part, remember to remove the handler afterward.

This is just part of my code extracted out, as an example...

$(div)
	.mousedown(function (e) {
		if (!leftButtonPressed(e)) {
			disableContextMenu(true);
			showOptions({ x: e.clientX, y: e.clientY }, div); // do my own thing here
		}
	});

When my showoptions() rtn finishes, a callback function is run and it calls the disable-rtn again, but with 'false':

disableContextMenu(false);

Here's my disableContextMenu() rtn:

function disableContextMenu(boolDisable, fn) {
	if (boolDisable) {
		$(document).contextmenu(function (e) {
			if (fn !== undefined) {
				return fn(e);
			} else {
				return false;
			}
		});
	} else {
		$(document).prop("oncontextmenu", null).off("contextmenu");
	}
}

Solution 12 - Javascript

There’s many Javascript snippets available to disable right-click contextual menu, but JQuery makes things a lot easier:

    $(document).bind("contextmenu",function(e){
        return false;
    });
}); 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTom GullenView Question on Stackoverflow
Solution 1 - JavascriptArsenyView Answer on Stackoverflow
Solution 2 - JavascriptArsen K.View Answer on Stackoverflow
Solution 3 - JavascriptKrisWebDevView Answer on Stackoverflow
Solution 4 - JavascriptSang SuantakView Answer on Stackoverflow
Solution 5 - JavascriptIan WoodView Answer on Stackoverflow
Solution 6 - JavascriptLukeView Answer on Stackoverflow
Solution 7 - JavascriptOlivier GrégoireView Answer on Stackoverflow
Solution 8 - JavascriptkacharView Answer on Stackoverflow
Solution 9 - JavascriptMirosław KarczmarczykView Answer on Stackoverflow
Solution 10 - JavascriptShrinathView Answer on Stackoverflow
Solution 11 - JavascriptDan KView Answer on Stackoverflow
Solution 12 - JavascriptJerry KingView Answer on Stackoverflow