In this tip, you will see a JavaScript code snippet to disable all links on the page.
Introduction
While working on one of the features asked by client to disable all the controls of the panel while an asynchronous operation is in process, I encountered that though link buttons are disabled (grayed out), they can still be clicked (thus they still work!). :(
I was looking into why such behaviour occurs and came across the link:
Disable All Links with JavaScript[^]
In order to disable all of the links on the page, we need to add an onclick
on all the link buttons and return false
. If there is an onclick
handler on that, we need to grab it and add it to the link.
Here is the code snippet for it:
window.onload= function(){
DisableEnableLinks(true)
}
function DisableEnableLinks(xHow){
objLinks = document.links;
for(i=0;i<objLinks.length;i++){
objLinks[i].disabled = xHow;
if(objLinks[i].onclick && xHow){
objLinks[i].onclick =
new Function("return false;" + objLinks[i].onclick.toString().getFuncBody());
}
else if(xHow){
objLinks[i].onclick = function(){return false;}
}
else if
(!xHow && objLinks[i].onclick.toString().indexOf("function(){return false;}") != -1){
objLinks[i].onclick = null;
}
else if(!xHow && objLinks[i].onclick.toString().indexOf("return false;") != -1){
strClick = objLinks[i].onclick.toString().getFuncBody().replace("return false;","")
objLinks[i].onclick = new Function(strClick);
}
}
}
String.prototype.getFuncBody = function(){
var str=this.toString();
str=str.replace(/[^{]+{/,"");
str=str.substring(0,str.length-1);
str = str.replace(/\n/gi,"");
if(!str.match(/\(.*\)/gi))str += ")";
return str;
}
History
- 25th February, 2010: Initial version