Following on from Jaspers comment on my blog post regarding my “newly discovered” way of creating new windows on links without using the target=”_blank” attribute, he posted a tidy bit of code based on Mootools that detects all <a> tags on his page, then opens in a new window if it starts with http:// (indicating it being an external link).
That’s cool. So I thought I would do the same using my preferred Javascript framework, jQuery. Here’s my code which has now been implemented on this site & looks like its working just fine…
$('.entry a').each(function(){
if ($(this).attr('href').substr(0,7) == 'http://')
{
$(this).addClass('new-window');
}
});
What we’re doing – top line, cycle through all <a> tags within the .entry class. Secondly, if the first 7 characters of the Href attribute within our <a> tag equals http://, then add a class to the <a> tag called new-window.
This will then be detected by my other small script on my page, as described here. Job done!
it didn’t come across too well because of the comment formatting, but I also put checking in there for the current domain to check for a true external link:
if (this.get(’href’).toString().match(/^http:\/\/[(www.)]*yourdomain\.com/) == null)
Ah indeed, I did notice something about do1.uk.com in there, but wasn’t quite sure what it was about. At the moment I’m just watching out when I create links in my posts to make sure the HREF attr begins with /page if its referencing a post or page on this site, or otherwise it’ll begin with http:// of course.
I guess what you’ve done there is a little more fool-proof, nicely done
Also, just a thought. What happens if I put in a link to http://www.bbc.co.uk/radio1 in the comments area… I’ll add the same jQuery code as above I think…. ?
Woordd! How’d you like those Apples!!
haha, works perfectly! Nice one!