views:

49

answers:

1

I'm fairly new to jquery and haven't had much time to explore more and was wondering if anyone could help me. Here is the code I have which I pulled from different places:

$("a").filter(function() {
                         return this.hostname && this.hostname !== location.hostname;
                         })
                         .attr({
                                target: "_blank"
                               });
                         $('a[rel*="external"]').live('click',function(){ this.target='_blank'; });

What I have this doing is whenever there is an A tag with href="http://" then it adds target="_blank" to it. If the href="http://" follows with the website URL you are on then it will not add target="_blank". On top of that if I want an internal page to open in a new window then I would add rel="external" to the A tag, which is then converted into target="_blank" on the live site.

How can I make it so that if I have a subdomain it will not open as an external page either. Say my url is example.com and the subdomain is test.example.com. So if I make a link from example.com to test.example.com then I do not want it to open in a new window. Also from test.example.com to example.com I would not want it to open in a new window either.

Also is this even a good approach? I write my sites in xhtml 1.1 and try to keep the pages valid. This will pass validation but it still adds target="_blank" to the ending result. Is this bad practice or acceptable?

Thanks for any advice.

A: 

Instead of checking for hostname equality, you could check to see if this.hostname ends with location.hostname. Unfortunately, JavaScript doesn't have an endsWith function but you can easily write one:

String.prototype.endsWith = function(that) {
    return this.lastIndexOf(that) == this.length - that.length;
};

Then, in your filter method:

return this.hostname && this.hostname.endsWith(location.hostname);

Links to subdomain.example.com end with example.com and so their target would be set.

Lobstrosity