I need to implement javascript only solution that would override default a href behavior, check if href location exist and then redirect to it or to 404.html. So far I come up with this:
function UrlExists(url)
{
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}
document.onreadystatechange = function()
{
var anchorElements = document.getElementsByTagName('a');
for (var i in anchorElements)
anchorElements[i].onclick = function()
{
if (UrlExists(this.href)) {window.location=this.href; }
else {window.location='404.html'=;}
return false;
}
}
However, if UrlExists()
gets called, default behavior is not overridden. Any ideas?
EDIT: 404 check works, and all links are on same domain Also non jQuery solution is preferred.
//UrlExists function was copied from Trip and jAndy