Ad

Monday 25 August 2014

To disable the contextmenu on rightclick of the link/anchor using jquery

    We sometimes need to disable the right click on the link due to security reasons, so that we don't show up the default context menu on our webpage. Using jQuery this can be easily implemented. Below is the sample page where we have two links(anchor) and we would need to disable the right click on the first link(Link1)

<html>
<head>                                                                                                                                                     
<title>To Disable right click</title>
<script type="text/javascript" src="jquery-2.1.1.min.js" ></script>
<script type="text/javascript">

$(document).ready(function() {

$('#link1').bind("contextmenu",function(e){
alert("Right click not allowed");
return false;
});


});
</script>
</head>
<body bgcolor=white>
<a href="#" id="link1">Link1</a>
<BR>
<a href="#" id="link2">Link2</a>
</body>
.

As we can see in the JavaScript, we registered the handler to the element of id "link1" for the eventType "contextmenu".So this handler will be called when we right click on the link "Link1" and since we return as false the context menu will not be displayed.

Demo
Link1
Link2

If our requirement is to disable the right click on the whole webpage, then we need to register the handler on the document object as shown below:

$(document).bind("contextmenu",function(e){                                                                                      
alert("Right click not allowed");
return false;
});
 

No comments:

Post a Comment