Is it possible to permanently change a javascript variable? As in, if I set the variable X and make that equal to 1. Then onClick of a button change that variable to 2. How can I get that variable to stay at 2 on refresh of the page?
This question is related to
javascript
html
You can do that by storing cookies on client side.
In addition to cookies and localStorage
, there's at least one other place you can store "semi-persistent" client data: window.name
. Any string value you assign to window.name
will stay there until the window is closed.
To test it out, just open the console and type window.name = "foo"
, then refresh the page and type window.name
; it should respond with foo
.
This is a bit of a hack, but if you don't want cookies filled with unnecessary data being sent to the server with every request, and if you can't use localStorage
for whatever reason (legacy clients), it may be an option to consider.
window.name
has another interesting property: it's visible to windows served from other domains; it's not subject to the same-origin policy like nearly every other property of window
. So, in addition to storing "semi-persistent" data there while the user navigates or refreshes the page, you can also use it for CORS-free cross-domain communication.
Note that window.name
can only store strings, but with the wide availability of JSON
, this shouldn't be much of an issue even for complex data.
You will have to use cookie to store the value across page refresh. You can use any one of the many javascript based cookie libraries to simplify the cookie access, like this one
If you want to support only html5 then you can think of Storage api like localStorage/sessionStorage
Ex: using localStorage and cookies library
var mode = getStoredValue('myPageMode');
function buttonClick(mode) {
mode = mode;
storeValue('myPageMode', mode);
}
function storeValue(key, value) {
if (localStorage) {
localStorage.setItem(key, value);
} else {
$.cookies.set(key, value);
}
}
function getStoredValue(key) {
if (localStorage) {
return localStorage.getItem(key);
} else {
return $.cookies.get(key);
}
}
Source: Stackoverflow.com