July 13, 2009
My code doesn't validate when I use a target attribute...
The target attribute has been depreciated.
“But how can I make links open in a new window?”
The answer is JavaScript, but it’d be a bitch to add an onclick attribute to every external link, so I wrote something with Prototype to do it for me.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
document.observe('dom:loaded',function(){ var domain = document.domain.sub('^http://','').sub('^www.',''); // get domain $$('a[href^=http]').each(function(el){ // get all links on the page var url = el.href.sub('^http://','').split('/').shift(); // get base url if(!url.match(domain+'$')) { el.observe('click',function(event){ Event.stop(event); window.open(el.href); // and open }); } }); }); |
It just checks the URL of your domain against the links on the page. If the link isn’t of your site window.open is called.
The only catch to the code is with sub-domains. The JavaScript looks at test.codequietly.com and codequietly.com as the same domain, since it kind of is.
Just a little something for ya.

Leave a Comment