views:

41

answers:

2

Im trying to take a link either when clicked or hover over be able to grab the attribute href and tell if its a hyper-link or not. Also i want it to be able to tell me if its a hyper-link to my own site. Plus various other filters.

The main purpose for this is so that when a internal link is clicked it will tell ajax to grab the content, alot of my links are generated (via wordpress)so I can't modify them too much. Another purpose for this is so i can also make all external links open on a new window.

I have a solution that works on a simple test page but when i put into a working page it breaks. I know i am probably making this harder then it should be.

Here is my code

$(function(){
   $('a').live('click', function(){
      var x = $(this).attr('href');

      $(this).parent('div').append('<div id="test">' + x +'</div>');
      $('#test:contains("http")').css('color', 'red');
      $('#test:contains("sitename")').css('color', 'black');
      $('#test:contains("admin")').css('color', 'red');
      if($('#test').css('color') == 'red'){

         alert('external link');
         $('#test').remove();
         return true; 

      }else{

         alert('external link');
         $('#test').remove();
         return false;

      }
   });
});

thanks for you help

+1  A: 
$('a').live('click', function(){
   var href = $(this).attr('href');

   if(/http:\/\//.test(href) || /admin/.test(href)){
      //alert('external link');
      $(this).attr('target', '_blank');
      return(true);
   }

   if(/sitename/.test(href)){
      //alert('internal link');
      $.ajax({});
      return(false);
   }       
}

that is a better approach I guess. Should work, but untested. The regex can/and should be fine tuned.

Kind Regards

--Andy

jAndy
a much better approach. thanks works like a charm.
Jacob Lowe
+1  A: 

You could also use the jQuery selector syntax (http://api.jquery.com/attribute-starts-with-selector/):

$('a[href^=http://], a[href^=/admin/]').live('click', function(){});
$('a[href^=/sitename/]').live('click', function(){});

If you checkout the selector API you'll find some more selectors (e.g. ends with X, contains X, etc.).

petergassner
this is useful information
Jacob Lowe