1 October 2013

Disable Right Click in webpage using jQuery

Hi Friends,

Let see how can we disable the "Right Click" in a web page using the jQuery.  Sometimes we need this snippet to prevent the user to perform few operations. But remember this is OK for normal user but for expert it would not work.  They know lot of way to show the context menu.

Well whatever lets see how can we disable the right click..
<html>
<head>
  <title>Right Click Disabled</title>
  <script src="https://code.jquery.com/jquery-1.9.1.js" type="text/javascript">
  </script>
  <script type="text/javascript">
    $(function () {
      // to disable the right click on whole web page
       $(document).bind("contextmenu",function(e){
         e.preventDefault();
         alert("Right Click is not allowed");
      });
     
     // to disable the right click on all the images use the below code
     
  /*
      $('img').bind("contextmenu",function(e){
         e.preventDefault();
         alert("Right Click is not allowed on images");
      });      
      */
    });
  </script>
</head>
<body style="height:400px; border:1px solid black;">
    This is the body content. 
    <img src="head.png" />
</body>
</html>
Without prompting any alert just to disable the right click you have to remove the alert box
$(function () {
      // to disable the right click on whole web page
       $(document).bind("contextmenu",function(e){
         e.preventDefault();
         alert("Right Click is not allowed"); 
      });
  });
Happy knowledge sharing.. :)

No comments:

Post a Comment