Can I count clicks on links with javascript?
I have created a click counter with local storage, so it can store the click counts.
<html>
<body>
<a href="#" onclick="clickCounter()">Click Counter</a>
<a href="#" onclick="resetCounter()">Reset Counter</a>
<br>
<p id="result"></p>
<script>
function clickCounter() {
var count = localStorage.clickcount = Number(localStorage.clickcount)+1;
if (isNaN(count) === true) {
count = localStorage.clickcount = 1;
document.getElementById("result").innerHTML = count;
} else {
document.getElementById("result").innerHTML = count;
}
}
function resetCounter() {
var reset = localStorage.clickcount = 0;
document.getElementById("result").innerHTML = reset;
}
</script>
</body>
</html>
Sure, add an onclick event handler function to the <a>
tag that retrieves, increments and stores a counter variable. You can retrieve and store this in a hidden field. You will lose the information once you navigate away from the page, however.