user759235
user759235

Reputation: 2207

jQuery: Easy way to check if a href attribute is valid

I am looking for a pretty easy way to check when somebody clicks a link that it's valid.

Good

 <a href="index.html">some link</a>

Bad:

<a href="#">some link</a>
<a href="javascript:void(0);">some link</a>

Upvotes: 3

Views: 3033

Answers (2)

Sarfraz
Sarfraz

Reputation: 382706

Just check for the href value:

$('a').click(function(){
  var bad = this.href.lastIndexOf('#') >= 0 || this.href.indexOf('javascript') >= 0;
  alert(bad ? 'Bad' : 'Good');
  return false;
});

Demo

Upvotes: 4

mas-designs
mas-designs

Reputation: 7536

There is no really "easy" way, you have to get the value of the href and do an ajax call to it like so :

var url = $('a').attr('href');
    $.ajax({
        url:url,
        type:'HEAD',
        error: function()
        {
            //file not exists
        },
        success: function()
        {
            //file exists
        }
    });

Upvotes: 3

Related Questions