I have the following code
<html>
<head>
<script>
var m=0;
function add() {
m++;
}
</script>
</head>
<body>
<button onclick="add();">click</button>
</body>
</html>
But if I refresh the page then again the value of m
starts from 0. How can I persist the value of m
between each load of the page on a client machine?
you can use cookies from javascript. check this link.
http://www.w3schools.com/js/js_cookies.asp
here is the working code sample:
<html>
<head>
<script>
var m=getCookie("m");
if(isNaN(m)) {
m=0;
}
function add()
{
m++;
alert(m);
setCookie("m",m,86400);
}
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
</script>
<body>
<button onclick="add();">click</button>
</body>
</html>
One way is cookie
document.cookie = 'foo,bar'
Another way to do is use localstorage
localStorage.setItem('foo', 'bar');
localStorage.getItem('foo'); // return 'bar'
Actually it is what js mean to do on browsers, don't fight it, live with it. If you want to store variables in browsers, use cookies or local-storage(html5) then.
You can't do that. The DOM and all the JS variables in your page get recreated on refresh. If you want to persist it you can either use cookies or localstorage to persist it.
It's normal that refreshing the page loads javascript functions again - use sessions or cookies to store variables like that.