Saturday, January 3, 2009

Disable Right Click using Javascript

Simple way yo disable right click:
<body oncontextmenu="return false;">


Using script:
<script>
var isNS = (navigator.appName == "Netscape") ? 1 : 0;
if(navigator.appName == "Netscape") document.captureEvents(Event.MOUSEDOWN||Event.MOUSEUP);
function mischandler(){
return false;
}
function mousehandler(e){
var myevent = (isNS) ? e : event;
var eventbutton = (isNS) ? myevent.which : myevent.button;
if((eventbutton==2)||(eventbutton==3)) return false;
}
document.oncontextmenu = mischandler;
document.onmousedown = mousehandler;
document.onmouseup = mousehandler;
</script>

From: http://www.reconn.us/content/view/36/45/


Now...
Can i disable right click only on images?
Yes, by using getElementsByTagName i can set no right click on images only

<script>
function noRtClk(){
return false;
}
//document.oncontextmenu = noRtClk;

var e=document.getElementsByTagName("img");
for(var i=0;i<e.length;i++)
{
e[i].oncontextmenu = noRtClk;
}
</script>

Reference: http://www.aglasshalffull.org/css-resources/Using-getElementsByTagName-and-getElementsByName.htm

Thats it.

No comments: