How to create a click counter that saves data in txt file even when refreshed

1.4k views Asked by At

I also want the link to actually work; right now just runs the javascript I want it to run that plus go to the webpage. I would like for the data to be saved to a text file. Please Help! Here is code:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<body>
//Would like the link to redirect to webpage too.
<p>
<a href="javascript:countClicks();">Click Here</a> 
</p>
<p id="p2">0</p>
<script type="text/javascript">
var count = 0;
function countClicks() {
 count = count + 1;
    document.getElementById("p2").innerHTML = count;
}
</script>
</body>
</html>
1

There are 1 answers

0
luc122c On

Cookies store data locally even when refreshed. If you want to store something simple like a number in the browser, I'd recommend using cookies. Mozilla have got them well documented here: https://developer.mozilla.org/en-US/Add-ons/Code_snippets/Cookies.

You'd want to set the cookie after setting the innerHTML, set the value to count. Then when the browser is refreshed, or onLoad(), read the cookie and set it's value to count and it will start off from there.

Despite what you may have heard, cookies are not dangerous, they are just a small file, only a few bytes, with a name, value and expiration date. They are simple to implement but they are not permanent, the user can delete or edit cookies. Hopefully this is what you are looking for.