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






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: