Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save the state of a javascript variable that is used in multiple html pages

I am trying to make an application in phonegap. I have made a custom.js javascript file which have some functions as

function func1(){....}
function func2(){....}

All these functions will be used in two different html pages. In first HTML page,I am using a variable in func1 which is doing some operation. In second page, I want to access it in func2 in the state in which he was in func1. But i am unable to do it. I am including custom.js in both html pages. I have read that javascript files get reset/refresh when used in multiple pages. Can anybody give me an example that how to save the state of variable in func1 and then access that variable in func2 (in different HTML page) in the state in which he was in func1. i have also read about view state. but it is not working either for me. Please help...

like image 544
Shahid Iqbal Avatar asked Oct 15 '12 12:10

Shahid Iqbal


People also ask

How do you store contents of a variable in HTML?

Answer: Use the concatenation operator (+) The simple and safest way to use the concatenation operator ( + ) to assign or store a bock of HTML code in a JavaScript variable. You should use the single-quotes while stingify the HTML code block, it would make easier to preserve the double-quotes in the actual HTML code.

How do I transfer data between two pages in HTML?

There are two ways to pass variables between web pages. The first method is to use sessionStorage, or localStorage. The second method is to use a query string with the URL.


2 Answers

Store the values in localstorage and reference it from there.

function first() {
    localStorage.setItem('myItem', "something you want to store");
}

function second() {
    myValue = null;
    if (localStorage.getItem('myItem')) {
        myValue = localStorage.getItem('myItem');
    }
}
like image 56
epascarello Avatar answered Oct 12 '22 23:10

epascarello


in modern browsers you can use localStorage for that

var get = function (key) {
  return window.localStorage ? window.localStorage[key] : null;
}

var put = function (key, value) {
  if (window.localStorage) {
    window.localStorage[key] = value;
  }
}

use get and put to store value to the local storage of most modern browsers..

like image 40
lrsjng Avatar answered Oct 12 '22 22:10

lrsjng