2

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

lazanet
  • 101
  • 6

1 Answers1

2

Thanks to RobM. and Script47 for pointing out that preventDefault is native function:

   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(th) 
        {
        th.preventDefault();
        if (UrlExists(this.href)) { window.location=this.href; }
        else {window.location='404.html';}
                return false;
            }
}
lazanet
  • 101
  • 6