Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does back/forward in the browser change javascript variables?

<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?

like image 548
TIMEX Avatar asked Feb 24 '10 02:02

TIMEX


People also ask

What happens when we press back button in browser?

A back button in the browser lets you back-up to the copies of pages you visited previously. The web browser's back and next buttons work well with web sites that provide information that changes infrequently, such as news and shopping web sites.

Can you change var in JavaScript?

In JavaScript, you can reassign values to variables you declared with let or var .

What is correct about variables in JavaScript?

A JavaScript variable is simply a name of storage location. There are two types of variables in JavaScript : local variable and global variable. There are some rules while declaring a JavaScript variable (also known as identifiers). Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.

What are the 4 ways to declare a JavaScript variable?

4 Ways to Declare a JavaScript Variable:Using var. Using let. Using const. Using nothing.


1 Answers

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>
like image 88
Trey Hunner Avatar answered Oct 06 '22 22:10

Trey Hunner