Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I share JS variables between pages?

So basically I have 2 html pages. 1 has a button and displays the numbers the button generates, the other page (2) only displays. Then I have a script.js file so both files can get the values there. The thing is that when I include page 2 on 1, it gets the values, but when separated from page 1, it doesn't get any values even with the same script.

So basically it's something like this

Page 1

id="nom" style="font-size: 100px; margin-bottom: 5px; text-align: center; font-family:Arial; background: #FFFFF">1

This one gets value from the button with the id (nom) and adds 1 to the number already there.

Page 2

Page two has the same code, but is not getting the values when i change them in page 1 with the buttons.

Script.js

document.getElementById("nom").innerHTML = parseInt(document.getElementById("nom").innerHTML) + 1;

The output is done like this. p id="nom">1

So, this is basically it, i can't get the values on page 2 when I change them in page 1. Any help?

like image 239
Miguel Avatar asked Jun 20 '18 09:06

Miguel


1 Answers

Store your variable value in localstorage like this:

Page 1

localStorage.setItem("key", "yourvalue");

page 2

document.getElementById("yourVariable").innerHTML = localStorage.getItem("key");

In your case, It will be:

Page 1

<html>
<head>Page 1</head>
<body>
<p id="nom">1</p>
<button onclick="YourFunctionName()">Your Button</button>

<script>
function YourFunctionName(){
    document.getElementById("nom").innerHTML = parseInt(document.getElementById("nom").innerHTML) + 1;
    localStorage.setItem("key", parseInt(document.getElementById("nom").innerHTML));
}
</script>
</body>
</html>

Page 2

<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>

</head>

<body>
<p id="nome"></p>

<script>
$(document).ready(function(){
    document.getElementById("nome").innerHTML = localStorage.getItem("key");
});
</script>
</body>
</html>
like image 118
Dhrutika Rathod Avatar answered Sep 28 '22 08:09

Dhrutika Rathod