Wednesday, February 10, 2010

Disable text selection and right click in html / asp.net 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.

Code:

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)
{
//document.onmousedown=disableselect
// the above line creates issues in mozilla so keep it commented.

document.onclick=reEnable
}

function clickIE()
{
if (document.all)
{
(message);
return false;
}
}

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

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


</script>



Add the below code into your Css :

body
{
-moz-user-select: none;
}


Note:
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