Wednesday, February 10, 2010

Disable text selection and right click in html / pages

If you want that your html page's content (text/images) should not be copied then you need to disable the right click and the text selection.

Most of the scripts are available on internet to do this but most of them are not cross browser compatible.

Disabling the right click works on all browsers,
but the text selection blocking javascript code in mozilla prevents click on the textboxes.
Means if you have blocked the textselection using the javascript you, will not be able to click on the search box, contact form textbox etc.

When i faced this issue i removed some events from javascript and used css to make it working.

Setting the -moz-user-select property to none , disables the text selection in Mozilla Firefox.


Place the below code in the head tag of html page:
<script language="JavaScript1.2" type="text/javascript">

function disableselect(e)

return false

function reEnable()

return true

//if IE4+

document.onselectstart=new Function ("return false")

//if NS6

if (window.sidebar)
// the above line creates issues in mozilla so keep it commented.


function clickIE()
if (document.all)
return false;

document.oncontextmenu=new Function("return false")

var element = document.getElementById('q');
element.onmousedown = function () { return false; } // mozilla


Add the below code into your Css :

-moz-user-select: none;

This code works with asp.netl php and all other languages as it's using just javascript and css.
Code is test and working in below browser:
1) Internet explorer (all versions)
2) Mozilla
3) Chrome
4) Safari

No comments: