Search code examples
jquerybindingreturnpreventdefaultright-click

How to add an exception to a jQuery that disables right-click?


I am trying to disable right-click in the whole page except for two elements that are meant to be copied. I know disabling right-click sounds like a bad idea about every time, but it makes sense to me in this case. I found some information about how to unbind elements to re-enable a behaviour that was prevented using preventDefault(); and also tried with return: true for the exceptions, but it wasn't successful. There's no trigger for re-enabling the right-click feature, it should be all at once.

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

I also tried this:

var disablerightclick = function(e) {
    e.preventDefault();      
}
$(document).ready(function() {  
    $(document).bind('contextmenu', disablerightclick);   
});
//]]>

It works everytime. But it doesn't let me unbind anything else directly below and it makes sense it doesn't, I will try something and update whether it works or not.

This is the update I mentioned previously. It doesn't work...

var disablerightclick = function(e) {
    return false;    
}
    $(document).ready(function() {
        $('img').mousedown(function(){return false});
        $('body').bind('contextmenu', disablerightclick);
    });
    $('#AnyObject').hover(function() {
        $('body').unbind('contextmenu', disablerightclick);
    });

I will keep trying since I am not getting any answer.


Solution

  • Just read this thread

    Use this code:

    $(document).on('contextmenu', function(e) {
        if (!$(e.target).is("#special"))
           return false;
    
        alert('#special right clicked');
        // you may want e.preventDefault() here
    });