In some situations some web admins think disabling a right click on their web page is a good idea.
The reason for disabling a right click could be to:
- protect and hide source code
- protect images on web page
- disable copy and paste functionality...
There are opinions that disabling right mouse click is a bad practice and you shouldn't do it on your site (find out why here). It can prevent some novice users from stealing on your site but more advanced users will find a way (to get image or take a look on your source code).
In this article you will find how to:
- disable right click on whole HTML web page using onmousedown event
- disable right click on whole page using attribute inside body tag
- disable right click on some part of HTML page
Here is a code:
Disable right click on HTML page using body attribute
This method prevents context menu to appear when right click happened without message box on HTML page. It is very easy to implement.
You just need to add this attribute to body element:
<body oncontextmenu="return false">
Disable right click on only part of HTML page
On the beginning of this article it was said that preventing users from using right click is a bad practice. So if you want to protect something on your page maybe is better practice to protect only this specific element.
It is possible to use oncontext attribute on specific HTML element.
To better explain we will show the example with HTML table with two columns. We will forbid right click only on First column. On Second column right click is possible.
<Table> <tr> <td oncontextmenu="return false"> First column (no right click) </td> <td> Second column </td> </tr> </Table>
On td tag attribute oncontextmenu is added and set to "return false". So on First column right click is disabled.
|No right click||Second column|
You can disable right click on image using the technique described in previous chapter. Just add oncontextmenu attribute inside img element.
<img src="../PathToImage" oncontextmenu="return false" />
On the beginning of the article you can find image "No right click!" which can not be right clicked.