0

I can't make this open the image in a new window (not tab).

This script is placed in <head>:

<script type="text/javascript">

  function randomImg1() {
    var myImage1 = new Array();
    myImage1[0] = "1.jpg";
    myImage1[1] = "2.jpg";
    myImage1[2] = "3.jpg";
    var random = Math.floor(Math.random() * myImage1.length);
    document.getElementById("image").innerHTML = "<img src='" 
      + myImage1[random] + "' alt='image'></img>";

  }

</script>

My button is placed in <body>:

<button onclick="randomImg1();OpenInNewTab();">click</button>    
<div id="image"></div>
Andrew Myers
  • 2,754
  • 5
  • 32
  • 40
  • 1
    you are writing an image tag in a DOM element with the ID "image". Try `window.open(myImage1[random])` instead. Though you might run into problems with popup blockers. – masterfloda Sep 19 '17 at 23:05
  • wher in the code should i add window.open(myImage1[random]) – Tommy Fabricius Sep 19 '17 at 23:12
  • replace `document.getElementById("image").innerHTML = "image";` with `window.open(myImage1[random]);` – masterfloda Sep 19 '17 at 23:14
  • 2
    PS: most browsers will open a new tab (not a window). To open a new window, you need to add the specs parameter. see https://stackoverflow.com/a/726803/7933618 and https://www.w3schools.com/jsref/met_win_open.asp – masterfloda Sep 19 '17 at 23:18
  • oh, and you probably need to specify the whole path to the image. Either hardcode it or if it's relative to the current location, you can use the current path with either `window.location.href` if you are on a "folder" level, or if your current URL contains a filename (like index.html), you can build the path like `window.open(window.location.protocol + '//' + window.location.host + window.location.pathname + myImage1[random]);` – masterfloda Sep 19 '17 at 23:21
  • 1
    Possible duplicate of [JavaScript open in a new window, not tab](https://stackoverflow.com/questions/726761/javascript-open-in-a-new-window-not-tab) – masterfloda Sep 19 '17 at 23:24

1 Answers1

0

Use https://www.w3schools.com/jsref/met_win_open.asp to open a new window. Add the spec parameter to make it open as a new window instead of a tab. And make sure to pass the full path of the image:

<script type="text/javascript">

  function randomImg1() {
    var myImage1 = new Array();
    myImage1[0] = "1.jpg";
    myImage1[1] = "2.jpg";
    myImage1[2] = "3.jpg";
    var random = Math.floor(Math.random() * myImage1.length);
    // create the full image URL
    var imageUrl = window.location.protocol + '//' + window.location.host + window.location.pathname + myImage1[random];
    // open in a new window. ideally use the image's size for w and h
    window.open(imageUrl, '_blank', 'height=300,width=300');
  }
</script>
masterfloda
  • 2,908
  • 1
  • 16
  • 27