Gaurav Mahajan
Gaurav Mahajan

Reputation: 109

Global variable in javascript (declare it from one file, put value from another file and accessing it from some another file)

I declared javascript global variable in global.js file eg:

var glbValue;

and putting the value of global variable glbValue from first.html eg:

<script type="text/javascript" src="global.js"></script>
<script type="text/javascript">
function onBtnSubmit()
{
   glbValue=123;
}
</script>

and accessing the global variable glbValue from second.html eg:

<script type="text/javascript" src="global.js"></script>
<script type="text/javascript">
function onBtnClick()
{
   alert(glbValue);
}
</script>

it gives me output undefined inplace of 123, why ?

Upvotes: 1

Views: 132

Answers (2)

Oscar Paz
Oscar Paz

Reputation: 18292

When a page loads, all its script files are executed in a new context. The browser does not 'remember' what you did in the last page. If you want to share a variable between pages, either you use cookies or, even better, localStorage or sessionStorage.

  1. Use localStorage if you want the value to be preserverd even when you close the browswer.
  2. Use sessionStorage if you want the value to be preserved only during the current session.

I think that the 2º solution is the best in your case:

first.html:

<script type="text/javascript">
function onBtnSubmit()
{
   sessionStorage.setItem('gblValue', 123);
}
</script>

second.html

<script type="text/javascript">
function onBtnClick()
{
   alert(sessionStorage.getItem('gblValue'));
}
</script>

You no longer need that global variable. The only problem with this solution is that IE8 and below do not support this, but there are good polyfills that use cookies transparently.

Upvotes: 2

R3tep
R3tep

Reputation: 12854

Try to use the local storage :

first.html :

localStorage.setItem("glbValue", "123");

second.html :

alert(localStorage.getItem("glbValue"));

Upvotes: 2

Related Questions