7
<script type="text/javascript>
var x = 0; //this occurs in the beginning of the page.

$("#button").onclick{
x = 1;
}

</script>

Let's say the variable "x" changes to 1. Then the user clicks a link. When the user clicks "back", will x be 0 or 1?

balupton
  • 47,113
  • 32
  • 131
  • 182
TIMEX
  • 259,804
  • 351
  • 777
  • 1,080

2 Answers2

22

As detailed in another question, the real answer to this question is it depends on the browser.

In Firefox and Opera, the below page will preserve the state of 1 if Set x is clicked, the link is clicked, and then the back button is pressed. However, in Chrome and IE6 the page will be reloaded and x will have the value of 0.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<input type="button" id="button" value="Set x">
<input type="button" id="check-x" value="Check x">
<a href="http://www.stackoverflow.com">Click Me</a>
<script>
var x = 0;

$("#button").click(function(){
    x = 1;
});

$("#check-x").click(function(){
   alert(x); 
});
</script>
Community
  • 1
  • 1
Trey Hunner
  • 10,975
  • 4
  • 55
  • 114
0

It will be 0. The browser does not cache the state of Javascript variables between page loads.

Update

This is not the case in browsers such as Firefox. Please see Trey's answer.

Community
  • 1
  • 1
Justin Ethier
  • 131,333
  • 52
  • 229
  • 284
  • That's weird, I must have done something wrong. Was my code below wrong? I don't do much javascript, just trying to see why I get different behavior. – Anthony Forloney Feb 24 '10 at 03:07
  • But sometimes clicking a link then clicking back won't result in a page load, as when the target of the link is a local anchor. – Sean Feb 24 '10 at 06:18
  • how can you be so sure? It's completely up to the browser if it wants to hold a snapshot of the JavaScript state. And some browser actually do that when pressing back. I've seen it in Chrome, for example. – Felix Mar 15 '11 at 09:28