1

Is it possible to pass variables between two different JS files without using Node js, only with vanilla JS? I am only doing this on client side, I am not using a server or anything else.

In the first file (first.js) I have this (shortened) bit of code:

function appendImg(){
  var img = document.createElement('img');
  img.src = tempImg.src;
  document.body.appendChild(img);
  createImg(index++);

  img.onclick = function(event){
    window.location.href = "second.html";
    }
}

Where "img" comes from a series of operations, src assigning, etc, from a given images array I wrote at the beginning of my file.

What I'm trying to do is, when I click a certain image, it redirects me to another HTML page, as you can see, where I would like to display the same image that was clicked.

I'm having trouble doing this, as my img variable is declared in a function, and the second JS file does not recognize it.

How could I change this?

Andra
  • 61
  • 1
  • 9
  • When you do this -> `window.location.href = "second.html";` Your browser page is reloading, everything you did in your function is now not in memory. Unless you make your website into a SPA, you will need to store this image somewhere first and then retrieve it again in the second page. – Keith Feb 18 '20 at 15:13
  • How could I do this? – Andra Feb 18 '20 at 15:17

2 Answers2

1

As @Keith said, you are reloading the page, so you lose all memory. Even if you put it in the global scope, where another function could read it, it is gone.

One approach you could use is to put some reference in the url parameters:

function appendImg(){
  var img
  img = document.createElement('img');
  img.src = tempImg.src;
  document.body.appendChild(img);
  createImg(index++);

  img.onclick = function(event){
    window.location.href = "second.html?img_src=" + tempImg.src;
    }
}

Then in the second page you write code to examine the url parameters of the location.

Josh Wulf
  • 4,727
  • 2
  • 20
  • 34
1

The quickest way to accomplish this is to pass your image as a query string value. For example:

 // Make the image name safe to include in a URL
 const imageUrl = encodeURIComponent(img.src);

 // Pass the image as a query string value
 window.location.href = `second.html?image=${imageUrl}`;

In the JavaScript on second.html, you need to parse the query string to get your image path. See: How can I get query string values in JavaScript?

Ed Lucas
  • 5,955
  • 4
  • 30
  • 42