Reputation: 12836
How can I trigger some action with right click after disabling the browser context menu ?
I tried this . . .
$(document).ready(function(){
$(document).bind("contextmenu",function(e){
$('.alert').fadeToggle();
return false;
});
});
Upvotes: 62
Views: 173450
Reputation: 253
I found this answer here and I'm using it like this.
Code from my Library:
$.fn.customContextMenu = function(callBack){
$(this).each(function(){
$(this).bind("contextmenu",function(e){
e.preventDefault();
callBack();
});
});
}
Code from my page's script:
$("#newmagazine").customContextMenu(function(){
alert("some code");
});
Upvotes: 2
Reputation: 10037
.contextmenu method :-
Try as follows
<div id="wrap">Right click</div>
<script>
$('#wrap').contextmenu(function() {
alert("Right click");
});
</script>
.mousedown method:-
$('#wrap').mousedown(function(event) {
if(event.which == 3){
alert('Right Mouse button pressed.');
}
});
Upvotes: 1
Reputation: 111
To disable right click context menu on all images of a page simply do this with following:
jQuery(document).ready(function(){
// Disable context menu on images by right clicking
for(i=0;i<document.images.length;i++) {
document.images[i].onmousedown = protect;
}
});
function protect (e) {
//alert('Right mouse button not allowed!');
this.oncontextmenu = function() {return false;};
}
Upvotes: 0
Reputation: 64
document.oncontextmenu = function() {return false;}; //disable the browser context menu
$('selector-name')[0].oncontextmenu = function(){} //set jquery element context menu
Upvotes: 1
Reputation: 25760
The function returns too early. I've added a comment to the code below:
$(document).ready(function(){
$(document).bind("contextmenu",function(e){
return false;
$('.alert').fadeToggle(); // this line never gets called
});
});
Try swapping the return false;
with the next line.
Upvotes: 50
Reputation: 151
Just use the event-handler. Something like this should work:
$('.js-my-element').bind('contextmenu', function(e) {
e.preventDefault();
alert('The eventhandler will make sure, that the contextmenu dosn't appear.');
});
Upvotes: 15
Reputation: 6062
Is contextmenu
an event?
I would use onmousedown
or onclick
then grab the MouseEvent
's button property to determine which button was pressed (0 = left, 1 = middle, 2 = right).
Upvotes: 0
Reputation: 827436
There is no built-in oncontextmenu event handler in jQuery, but you can do something like this:
$(document).ready(function(){
document.oncontextmenu = function() {return false;};
$(document).mousedown(function(e){
if( e.button == 2 ) {
alert('Right mouse button!');
return false;
}
return true;
});
});
Basically I cancel the oncontextmenu event of the DOM element to disable the browser context menu, and then I capture the mousedown event with jQuery, and there you can know in the event argument which button has been pressed.
You can try the above example here.
Upvotes: 107