Reputation: 35
I'd like to put a link on a webpage and show a count of the number of clicks that link has received. Here's my current code:
<!DOCTYPE html>
<html>
<head>
<script>
function clickCounter() {
if (typeof (Storage) !== "undefined") {
if (localStorage.clickcount) {
localStorage.clickcount = Number(localStorage.clickcount) + 1;
} else {
localStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = localStorage.clickcount;
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
}
window.location = 'http://www.google.com';
}
</script>
</head>
<body link="White">
<p align="center">
<p>
<button onclick="clickCounter();"><span style="font-size:35px;" font face="Face"> Please Click Here to Access QLM </span>
</button>
</p>
<div align="center" id="result"></div>
</html>
So, the problem is how to make "result" text visible before we click the button?? because when I run that script, the "result" text its not appear until I click the button.
Upvotes: 0
Views: 7736
Reputation: 2229
window.onload=function(){
if( localStorage.clickcount) //for undefined result
document.getElementById("result").innerHTML = localStorage.clickcount;
};
Upvotes: 1
Reputation: 17765
This is the wrong way to go about solving this problem, as using localStorage will show each user the number of times that they have clicked the link themselves.
To track total clicks, what you need to do is use a server-side technology, for example on click fire off an ajax request to a PHP script which will record the total amount of clicks in a text file or database or something.
If you are doing this to obtain any serious kind of metrics, you'd be better off going down an established route such as Google Analytics: https://developers.google.com/analytics/devguides/collection/gajs/eventTrackerGuide
Upvotes: 0
Reputation: 1345
with jquery..
<script>
$( document ).ready(function() {
$('#result').html(localStorage.clickcount);
});
</script>
Upvotes: 0
Reputation: 1548
window.onload=function(){
document.getElementById("result").innerHTML = localStorage.clickcount;
};
You have to put the code to fill the result in the onload function to show it when the page is loaded.
Upvotes: 1