Skip to content
Advertisement

How do I make a JS function triggered in one HTML page edit elements defined in a second HTML page?

Basically I have two HTML pages, and both are connected to the same JS file. I want a function triggered by an event handler element in the first HTML to edit an element in the second HTML page, and then open it.

Here’s a very basic example:

$("#p1").click(function() { 
   $("#p2el").text("TEST");
})
<button id="p1">CLICK</button>

In this example, the button p1 is defined in the first HTML, and the p2el element is defined in a second HTML page, both linked to the same JS file.

In the above example, I also used location.href inside the function. The idea being that, the element is edited, and automatically the second HTML page is loaded.

It’s not working, and I don’t know why. The second HTML page loads, but the element p2el is not edited.

I suspect this is has to do with data not transferring to the second HTML, but I am not sure why and what is happening exactly. I tried using localStorage inside the function, and then use the stored data as a condition that edits the element in the second HTML page…

    function second() {
      if(localStorage["key"] == "on") { 
        $("#p2el").text("TEST");
        location.href = "secondpage.html"
     }
    }
   
   $("#p1").click(function() { 
       localStorage["key"] = "on";
       second()
    })
    

… but It didn’t work.

I hope somebody can help me out.

Advertisement

Answer

Navigating to a new page completely resets the “JavaScript envirionment”.

Your JS files are reloaded, everything starts anew. Some things persist through page loads, such as local storage and cookies, but function calls certainly don’t.

To do what you want to do, you’ll need to:

  1. Listen to the click event, and save the fact it was clicked somewhere.
    (You’re already doing this)
  2. On page load, check the storage to determine whether or not the button was clicked at some time. If it was, do whatever you want. You will probably want to reset the stored value so this happens only once.

This will probably do the trick for you:

if(localStorage["key"] === true) { 
  localStorage["key"] = false; // reset the key.
  $("#p2el").text("TEST");
}

$("#p1").click(function() { 
  localStorage["key"] = true;
  location.href = "secondpage.html"
});
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement