Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable right click on a specific div [duplicate]

Tags:

javascript

I am looking for a solution to disable right click over a specific div. I have this code that does this, but it also display an alert (i fixed this) and it works on the whole page.

    <script language="JavaScript">
<!--
//Disable right mouse click Script
//By Oscar Frank
//For full source code, visit http://www.oscarmini.com
var message="";
///////////////////////////////////
function clickIE4(){
if (event.button==2){
return false;
}
}
function clickNS4(e){
if (document.layers||document.getElementById&&!document.all){
if (e.which==2||e.which==3){
return false;
}
}
}
if (document.layers){
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown=clickNS4;
}
else if (document.all&&!document.getElementById){
document.onmousedown=clickIE4;
}
document.oncontextmenu=new Function("return false")
// -->
</script>

Can someone help me make this work only one or more specific divs? Thanks! I am a noob.

like image 817
Alex Stratov Avatar asked Jan 16 '18 11:01

Alex Stratov


2 Answers

On the div that you are trying to disable right click events, you can just add this:

oncontextmenu="return false;"

Example:

<div oncontextmenu="return false;">This div won't have the right click menu</div>
like image 86
Alexandre Canijo Avatar answered Nov 10 '22 06:11

Alexandre Canijo


You have to add an event on the specific div ( you can get the div by id document.getElementById ) and add an event listener for contextmenu. Example:

    document.getElementById("divId").addEventListener("contextmenu ", function(){
       console.log("Right Click");
       return false;
    });
like image 33
Thanasis Arvanitis Avatar answered Nov 10 '22 06:11

Thanasis Arvanitis