« Return to Thread: Change href of external links

Re: Change href of external links

by Paul McLanahan :: Rate this Message:

Reply to Author | View in Thread

For further clarification, here's some sample (untested mock up) code
that is a jQuery version of something I did a while back:

allowedDomains = ['mydomain.com','myotherdomain.net'];
$('a[@href^="http"]').each(function(){
        var isExt = true;
        for(var i=0;i<allowedDomains.length;i++){
                if(this.href.indexOf(allowedDomains[i])>-1){
                        isExt=false;
                        break;
                }
        }
        if(isExt){
                $(this).click(function(){
                        window.open(this.href);
                        return false;
                });
        }
});

That way you can set up whatever strings you want to allow to be
excluded in the allowedDomains array thus ensuring that the links you
find really are external to your site's domain(s).

On 11/28/06, Paul McLanahan <pmclanahan@...> wrote:

> Actually, you have to check for href attribs that start with "http"
> but then make sure that they're not "http://yourdomain.com" because IE
> will translate relative links into absolute ones in the returned
> string from aTagRef.href. I'd also make sure that they don't start
> with "javascript:" and "mailto:".
>
> On 11/28/06, Sam Collett <sam.collett@...> wrote:
> > On 28/11/06, agent2026 <adamd@...> wrote:
> > >
> > > Hi all,
> > >
> > > New to jQuery, and I'm trying to use it to set my external links to open a
> > > new window without using any attributes to  mark the external links.  I can
> > > do this with regular js, using a.href.match, but I can't get it to work with
> > > jQuery.  Tried various directions, but no go.
> > >
> > > Sure I'll feel pretty stupid when this is answered, but here is my ugly,
> > > non-functioning code:
> > >
> > > $(function(){
> > >     if ($!("a").href.match("http://www.internal.com")) {
> > >         $("a").click(
> > >              function() {
> > >                  window.open(this.href); return false;
> > >                  console.log("external");
> > >              };
> > >         );
> > >     };
> > > });
> > >
> > >
> > >
> > > Thanks for any help,
> > > Adam
> > > --
> >
> > This may work (untested), grabs all anchors that don't begin with http
> > (internal links should be referred to using '../../foo.html' or
> > '/bar.jpg'):
> >
> > $("a").not("[@href^=http]").click(
> >     function(){
> >         window.open(this.href);
> >         console.log('external');
> >         return false;
> >     }
> > )
> >
> > $("a:not[@href^=http]") may also work.
> >
> > _______________________________________________
> > jQuery mailing list
> > discuss@...
> > http://jquery.com/discuss/
> >
>

_______________________________________________
jQuery mailing list
discuss@...
http://jquery.com/discuss/

 « Return to Thread: Change href of external links