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 might have to use:
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.
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.
One way is cookie
Another way to do is use localstorage
It's normal that refreshing the page loads javascript functions again - use sessions or cookies to store variables like that.
you can use cookies from javascript. check this link.
http://www.w3schools.com/js/js_cookies.asp
here is the working code sample: