Using the script you have as an example just set a conditional. I used the inArray()
function described here. The basic logic is to set an array called good_links
that is a list of links you do not want neutralized. And then by using the inArray()
function, the disable()
function can now logically traverse all links but ignore the good_links
:
<script type="text/javascript">
function disable(){
var good_links = new Array();
good_links[0] = "http://www.google.com/";
good_links[1] = "http://www.yahoo.com/";
good_links[2] = "http://www.bing.com/";
links=document.getElementsByTagName('A');
for(var i=0; i<links.length; i++) {
if (!inArray(links[i].href, good_links)) {
links[i].href="javascript:return false";
}
}
}
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}
window.onload=disable;
</script>
Okay, here is my whole HTML file which works. The only links that should work are: Google, Yahoo & Bing. Apple, Catmoji & StackOverflow are disabled.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My Webpage</title>
<script type="text/javascript">
//<![CDATA[
function disable(){
var good_links = new Array();
good_links[0] = "http://www.google.com/";
good_links[1] = "http://www.yahoo.com/";
good_links[2] = "http://www.bing.com/";
links=document.getElementsByTagName('A');
for(var i=0; i<links.length; i++) {
if (!inArray(links[i].href, good_links)) {
links[i].href="javascript:return false";
}
}
}
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}
window.onload=disable;
//]]>
</script>
</head>
<body>
<a href="http://www.google.com/">http://www.google.com/</a><br />
<a href="http://www.apple.com/">http://www.apple.com/</a><br />
<a href="http://www.yahoo.com/">http://www.yahoo.com/</a><br />
<a href="http://www.catmoji.com/">http://www.catmoji.com/</a><br />
<a href="http://www.bing.com/">http://www.bing.com/</a><br />
<a href="http://www.stackoverflow.com/">http://www.stackoverflow.com/</a>
</body>
</html>