Convert all Links to Open in a New Page

I was working on an existing website recently. The website had a few pages with a couple of hyperlinks leading to Customers websites. Clicking on the hyperlink would renders the content in the same window. The client now wanted that without any code change, all the links should open in a new window, so that the user remains on the main site, as well as also view the Customers website.

Here’s how this requirement can be achieved using jQuery

<!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 src="Scripts/jquery-1.3.2.js"
type="text/javascript"></script>
<
script type="text/javascript">
$(document).ready(function() {
$("a").each(function() {
$(this).attr("target", "_blank");
});
});
</script>
</
head>
<
body>
<
div>
<
a href="http://www.dotnetcurry.com">DotNetCurry</a><br />
<
a href="http://www.sqlservercurry.com">SQL Server</a><br />
<
a href="http://www.devcurry.com">DevCurry</a><br />
</
div>
<
br />
</
body>
</
html>


Observe that using jQuery, we set the target property of all the hyperlink to _blank, which renders content in a new window. Here are the values of the Target property

_blank - Renders the content in a new window without frames.

_parent - Renders the content in the immediate frameset parent.

_self - Renders the content in the frame with focus.

_top - Renders the content in the full window without frames

If you want to achieve the same in an ASP.NET page, just replace the links with an ASP.NET Hyperlink.



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: