One can disable the right click on an object by just specifyingoncontextmenu= “return false;” on the HTML object. If you want to disable the right click option on the whole web page, then use has to call above event on the html <body> tag e.g. <body oncontextmenu= “return false;”>.
You can perform certain task on right click by calling other function(s) on the event “oncontextmenu”.
|
Here is a code sample that shows how to disable default right click menu of the web page and add custom defined context menu to an object.
My_Context_Menu.html
|
<!-- Create custom contextmenu for an object --> <html> <head> <title>Custom Context Menu</title> <script language='JavaScript'> <!-- // Get the left offset of the object function getPosX(obj) { var curleft = 0; if(obj.offsetParent) while(1) { curleft += obj.offsetLeft; if(!obj.offsetParent) { break; } obj = obj.offsetParent; } else if(obj.x) { curleft += obj.x; } return curleft; } // Get the top offset of the object function getPosY(obj) { var curtop = 0; if(obj.offsetParent) while(1) { curtop += obj.offsetTop; if(!obj.offsetParent) { break; } obj = obj.offsetParent; } else if(obj.y) { curtop += obj.y; } return curtop; } // Pulldown the context menu list on right click function showContextMenu(){ document.getElementById('contextMenuList').style.display='block'; //Change the position of the "contextMenuList" Div var obj = document.getElementById('webObject'); var y1 = getPosY(obj); var x1 = getPosX(obj); document.getElementById('contextMenuList').style.left = (x1 + 30)+'px'; document.getElementById('contextMenuList').style.top = (y1 + 80)+'px'; } // Hide the context menu if user clicks any where on the screen. document.onclick= function() { document.getElementById('contextMenuList').style.display='none'; }; // Disable the right click on the entire web page. This is an optional step to be done, if you want to disable the default context menu. document.oncontextmenu= function() { return false; } --> </script> <!-- Define styles for your context menu list --> <style type="text/css"> <!-- .menuContainer { position: absolute; display: none; width: 150px; left: 100px; top: 300px; background-color: #FFFFFF; border: 1px solid #7B7B7B; padding: 0px; font-family: Arial; font-size: 70%; font-weight: Bold; color: #000000; } .menuStyle { padding: 2px; background-color: #D4D0C8; cursor: pointer; } .menuOutLine { padding-left: 1px; padding-right: 1px; padding-bottom: 1px; background-color: #FFFFFF; } --> </style> </head> <body> <p> Right click on the image to populate the context menu </p> <img src="myPicture.gif" id="webObject" oncontextmenu="showContextMenu();return false;"> <!-- Right click menu list --> <div id="contextMenuList"> <div style="padding: 1px; background-color: #FFFFFF;"><div>Save As..</div></div> <div><div>Zoom</div></div> <div><div>Print Picture</div></div> <div><div>Set As Background</div></div> <div><div>Properties</div></div> </div> </body> </html>