Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count clicks with javascript?

Tags:

javascript

Can I count clicks on links with javascript?

like image 612
user719813 Avatar asked Dec 06 '22 21:12

user719813


2 Answers

You can count clicks within a single request (for example, how many times a button was clicked after the page loaded). You cannot count clicks across requests (after you load another page or reload the current page).

Example:

<script type="text/javascript">var clicks = 0;</script>
<input value="Click" type="button" onclick="clicks++">

UPDATE:

You can also use the following (using jQuery) to persist it using cookies as recommended by others:

onclick="$.cookie('clicks', $.cookie('clicks') + 1);"
like image 62
Abdullah Jibaly Avatar answered Dec 26 '22 10:12

Abdullah Jibaly


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.

like image 36
Nick Rolando Avatar answered Dec 26 '22 10:12

Nick Rolando