Novice
Novice

Reputation: 161

Opening each link in a each new window

I would like to know how to open each link in a each new window (not Tabs).

I have around 4 links and I used the below sort of code.

<a href="Images\Chapter1.pdf"
onclick="window.open(this.href, 'new window','width=1000,height=600'); return false;">

I have 4 links and the above code works to some extent.

When I press any of these 4 links then a new window is going to open the pdf document but when I click on the 2nd link then the opened window is changing it's content to 2nd pdf but I would like to have two new short windows with the content but not only one new window changing it's Content.

(Target="_Blank" will open the content in a new tab but not in a new window).

Let me know how to overcome this issue.

Upvotes: 1

Views: 149

Answers (2)

mplungjan
mplungjan

Reputation: 178421

Try this (note will not work inside SO's editor) - the code will give a new name to each window:

var wins = [];
window.onload = function() {
  var links = document.querySelectorAll(".pdfLink");
  for (var i = 0; i < links.length; i++) {
    links[i].onclick = function() {
      var idx = wins.length;
      wins[idx] = window.open(this.href, 'newwindow' + idx, 'width=1000,height=600');
      return false;
    }
  }
}
<a href="Images\Chapter1.pdf" class="pdfLink">PDF1</a>
<a href="Images\Chapter2.pdf" class="pdfLink">PDF2</a>
<a href="Images\Chapter3.pdf" class="pdfLink">PDF3</a>
<a href="Images\Chapter4.pdf" class="pdfLink">PDF4</a>

If you want to allow the page to open even if there is a popup blocker, try this:

var wins = [];
window.onload = function() {
  var links = document.querySelectorAll(".pdfLink");
  for (var i = 0; i < links.length; i++) {
    links[i].onclick = function() {
      var idx = wins.length;
      wins[idx] = window.open(this.href, 'newwindow' + idx, 'width=1000,height=600');
      return wins[idx]?false:true;
    }
  }
}
<a href="Images\Chapter1.pdf" class="pdfLink" target="_blank">PDF1</a>
<a href="Images\Chapter2.pdf" class="pdfLink" target="_blank">PDF2</a>
<a href="Images\Chapter3.pdf" class="pdfLink" target="_blank">PDF3</a>
<a href="Images\Chapter4.pdf" class="pdfLink" target="_blank">PDF4</a>

Also note that you can write

    links[i].onclick = function(e) { 
      e.preventDefault();

and remove the return false - since we use querySelectorAll, the preventDefault is supported in the same browsers

Upvotes: 3

d4kris
d4kris

Reputation: 538

You are opening a new window with the name 'new window'. On the second click, you specify the same window.

If you use a new name in each call, they should open in separate windows.

Upvotes: 1

Related Questions