Using jQuery to Open External Links in a New Window - Expression Web

Posted by: Minal Agarwal , on 5/17/2010, in Category Expression Web
Views: 105242
Abstract: This article is about using jQuery to open external links on your page in a new window.
Learning jQuery has been on my to-do list from quite some time and finally, I am getting some hands-on with it. Suprotim’s eBook ’51 Recipes using jQuery and ASP.NET Controls’ has been very helpful and I am learning how to apply these tricks on my HTML web pages created using Expression Web. If you are new to jQuery, check this article ‘How jQuery Works
jQuery is a fast, lightweight JavaScript library that is CSS3 compliant and supports many browsers. The jQuery framework is extensible and very nicely handles DOM manipulations, CSS, AJAX, Events and Animations. While I continue my exploration with jQuery, I would like to share whatever I have learnt about jQuery with my readers.
This article is about using jQuery to open external links (links that point to a domain other than yours) in a new window.
I usually like to open up a link on a website in a new tab or a new window. This makes it easier for me to remember where I was and I always have the original page opened with me. There are some sites which contain links that open in the same window, and one link leads to another and I keep browsing pages in the same window. At some point, I realize I need to go back to the original page I visited and I don’t remember the URL. So I need to hit the back button on the browser several times, until I reach that page.
Now if you are building your website in Expression Web, you can open links in a new window using the ‘Hyperlink Properties’.
Select the hyperlink, right click and choose Hyperlink Properties from the menu. In the Edit hyperlink window, choose ‘Target Frame’. In the Target Frame window, select New Window from the list.
TargetFrame
Essentially we are setting the ‘target’ attribute to ‘_blank’ here.
But what if your page has many links on it and has already been created without the target=_blank attribute? In that case you will have to go to each link and change the code. Not very feasible, I say.
Enter jQuery! With a few lines of jQuery code, you can target all links on a page to open in a new window. If you are working on Master Pages, you can do it across the site. So now add the following jQuery script to the page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Open all Links In New Window</title>
 
    <script type="text/javascript"
        src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js">
    </script>
     $(document).ready(function() {
            $("a").each(function() {
                $(this).attr("target", "_blank");
            });
        });
    </script>
</head>
<body>
<div>
<a href="http://www.dotnetcurry.com/About.aspx">DotNetCurry</a><br />
<a href="http://www.saffronstroke.com">SaffronStroke</a><br />
<a href="http://www.devcurry.com">DevCurry</a><br />
</div>
<br />
</body>
</html>
Observe this piece of code.
$("a").each(function() {
                $(this).attr("target", "_blank");
});
 
What we are doing here is applying the target=_blank attribute to every anchor element on the page. This is achieved using the $.each() function which makes looping constructs very easy. We just select the anchors and iterate across them. As given in the documentation – “Each time the callback runs, it is passed the current loop iteration, beginning from 0. More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element
Open only External links in a new window
 
The code we saw above, will be applied to all links, internal and external to the site. Some people prefer to open internal links of the website in the same window, which may be advisable if you do not want the user to have too many new windows opened. But you would certainly want all external links to open up in a new window. This is a method adopted by many webmasters to engage audiences for a larger amount of time on their websites.
Here is how we can apply jQuery selectors to achieve this. Just change the following code from
$("a").each(function() {
    $(this).attr("target", "_blank");
})
to
$("a[href^='http:']:not([href*='" + window.location.host + "'])").each(function() {               
        $(this).attr("target", "_blank");
    });
})
Observe the a[href^='http:']:not([href*='" + window.location.host + "'])"). What this selector does is selects all anchor elements on the page that have the href attribute with a value beginning exactly with ‘http’ . We then use the :not() selector to match all elements that do not match the window.location.host property.
So for the domain http://www.dotnetcurry.com , dotnetcurry is the value for the window.location.host property. Since external links will never match the window.location.host of your site, all such links will be opened up in a new window. In the html code shared in the beginning of the article, SaffronStroke and DevCurry are external links
Note: If you are dynamically adding links to your page, then use the .live() method. The live() method is able to affect elements that have not yet been added to the DOM.
I hope you have realized how cool and powerful jQuery is and how we can use it to build some cool webpages created using Expression Web or any other editor.
You can see a Live Demo.
I hope you liked this article and I thank you for viewing it.
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by Asp Dot Net Developer on Monday, May 24, 2010 9:41 AM
This coding is more helpfull for me as well as all the asp.net developers also..
thank you very much..
Comment posted by carlton addison on Friday, June 18, 2010 12:26 PM
But what if I cannot edit the source on a sharepoint site. Can i enter in a script in a content editor web part to change the code?
Comment posted by Praveen on Saturday, June 26, 2010 3:18 PM
Good one. I think, this post describes good about it and a perfect solution too!!!

http://praveenbattula.blogspot.com/2010/06/open-all-anchor-links-in-new-window.html
Comment posted by sunce on Monday, September 5, 2011 1:08 AM

http://www.dotnetcurry.com/showarticle.aspx?id=510
Comment posted by Johnny Bananas on Saturday, November 12, 2011 5:40 AM
Fantastic script but i'd tweak it slightly so it allows you to open social media share links in a new window eg. http://www.facebook.com/sharer.php?u=the-url&amp;t=the-title. Currently if any existence of the host url exists then the script doesnt work like it should. This should fix the issue
$("a[href^='http:']:not([href^='http://" + window.location.host + "'])").each(function() {
                $(this).attr("target", "_blank");
    });
This means as long as the link doesnt start with the window.location.host property it opens in a window other it doesnt before the example link would open in a new window as the url contained the window.location.host property in the query string part of the url.

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel