Change click()
to almost anything but that. I suggest incrementClick()
. click()
is a reserved function in JavaScript.
<html>
<head>
<title>Space Clicker</title>
</head>
<body>
<script type="text/javascript">
var clicks = 0;
function incrementClick() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
</script>
<button type="button" onClick="incrementClick()">Click me</button>
<p>Clicks: <a id="clicks">0</a></p>
</body></html>
For persisting the clicks across page refresh, I suggest using cookies to save the current value of the click variable, like this (ref):
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else {
expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}
Reading cookies:
function getCookie(c_name) {
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return "";
}
Demo with cookie support: http://jsbin.com/rekafi/4
Note: I suggest you move away from including inline JavaScript in your <button>
element (e.g. onClick="incrementClick()"
). Try to keep your JS separate from your HTML using jQuery, for example.