Wednesday, February 23, 2011

Blogger: JQuery External Links in a New Window

Around the beginning of the year I introduced a simple javascript to automatically update links to another domain contained in the blog section to open in a new window. This script worked pretty well, but had a drawback of relying on the onload event for the page body. As a result for some time while a page loaded, links would remain unchanged. In order to address this shortcoming I've improved my method with the use of JQuery.

Installation is a cinch, simply copy and paste the following code into your blog template just below the <head> tag:
<script src='http://code.jquery.com/jquery-latest.js'/>
<script type='text/javascript'>
//<![CDATA[

function jqFixLink() {
 var strLink = $(this).attr("href");

 if(strLink != undefined) {
   if(strLink.search(document.domain) == -1 && strLink.indexOf("http:") != -1) {
     $(this).attr("target", "_blank");
   }
 }
}
function jqFixExtLinks() {
  $("#Blog1 a").each(jqFixLink);
}
$("#Blog1").ready(jqFixExtLinks);

 //]]>
 </script>
In Closing
That's all it takes, now as soon as your Blog widget loads all of its HTML this script runs. Only links pointing to another domain are affected, everything to other parts of your blog works normally. However, I should point out this introduces a small dependency by linking directly to the JQuery library. If their site doesn't respond for any reason, the script will fail, but in my experience that is an uncommon event. Give it a try and enjoy!
6 Comments
Comments

6 comments :

Chathuranga said...

If i use this code then Adsense links also open in new tab or window?

Chathuranga said...

It works fine. Many thanks buddy! Its really helpful post.

Kristen said...

If JQuery fails, will all my external links not be able to load, or will they just open in the same window of my blog?

Unknown said...

@Kristen, if for some reason the JQuery site is inaccessible the links will open as if the script never ran. So, in the same window.

Chathuranga said...

First of all i want say thank you for this script. It really work, sometime its not work. I have 2 questions regarding this script.
1).This script some extend slow down my blog loading time, so is it OK if i added this code before the "/body". Because if i added this code before the "/body" some extend page loading time increase.
2).Why sometimes this code not work properly?

Unknown said...

Loading slow down or failure is most likely a timeout loading the JQuery library from their servers. Alternatively, you may download JQuery and save it to your own hosting location such as Google code or locate a copy elsewhere.

Once JQuery is loaded, the script should execute quite quickly even with hundreds of links on each page. Few operations are performed per link.

Post a Comment