Open All Hyperlinks at Once using jQuery – the right way

If you have a bunch of hyperlinks on the page and you try opening them by using $(“a”).click(), they won’t open. This is because you need to first define a click event on that element.

Here’s a solution (shared originally by Owen) that works:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Open all Hyperlinks at Once</title>
<
script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js">
</
script>
<
script type="text/javascript">
$(function() {
$("#open").click(function() {
$("a").click();
});

$("a").click(function() {
window.open($(this).attr('href'));
});
});
</script>
</
head>
<
body>
<
a href="http://www.dotnetcurry.com">DotNetCurry</a>
<
a href="http://www.devcurry.com">DevCurry</a>
<
a href="http://www.sqlservercurry.com">SQLServerCurry</a>
<
input id="open" type="button" value="Open All" /><br />
</
body>
</
html>

See a Live Demo

You may also want to look at Convert all Links to Open in a New Page



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: