« Return to Thread: Change href of external links

Re: Change href of external links

by dave.methvin :: Rate this Message:

Reply to Author | View in Thread

> When testing, keep in mind that browsers behaviour
> with href attributes is quite inconsistent. While some
> return only the value as found in the markup, others
> add the domain and protocol.

Right, IE usually adds the base href to relative URLs. I think this would
work in all browsers:

 $("a[@href^=http]")
   .not("[@href*='internal.com/']")
   .bind("click", "!window.open(this.href)");

That's the short (and a hair slower) form of this:

 $("a[@href^=http]")
   .not("[@href*='internal.com/']")
   .bind("click", function(){
       return !window.open(this.href);
   });

By applying the not (!) operator to window.open it returns false to stop the
default action only if the window opens; if a popup blocker intervenes,
window.open returns null and the click handler will return true to allow the
default action--following the link.

Theoretically, .not("[@href*='internal.com/']") could incorrectly match some
non-local URLs if  "internal.com/" was outside the domain name; it shouldn't
be in the query string because "/" should be encoded there. So it seems
pretty safe to use this.

Another approach would be to define a target attribute on the external links
and the browser will open them in a new tab or window:

 $("a[@href^=http]")
   .not("[@href*='internal.com/']")
   .attr("target", "_blank");



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

 « Return to Thread: Change href of external links