5

Can I count clicks on links with javascript?

4
  • How do you mean count clicks? You mean like checking for a double or triple click, or just counting how many times onClick is triggered? Commented May 2, 2011 at 21:42
  • You have to explain a bit more. What is the context? Commented May 2, 2011 at 21:42
  • 1
    "can anyone post some resources which talk about this?" Sure: google.com Commented May 2, 2011 at 21:52
  • 3
    i searched for this on google, but i couldnt find it. That's why i referred to stacksoverflow. Please post helpful comments. Commented May 2, 2011 at 21:56

9 Answers 9

9

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);"
Sign up to request clarification or add additional context in comments.

1 Comment

Well, the asker could use a cookie to accomplish between page counting depending on the context.
2

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.

9 Comments

but if i use cookies to save the variable, will it remain the next time the page is visited?
Yes you can store the data in a cookie.
@user733618 Definitely. In that case the retrieve and store process would be with the cookie and not a hidden label!
one more question, what if the link isn't a link. Like, what if I have the text "blabla . com/" but it isnt linking to anything, in other words, no href tag, can i still count the clicks on it?
If you don't have an href attribute, it won't be clickable. So I don't think it will fire its onclick event. You could use a button instead to do this :)
|
2

You can use this:

const btn = document.querySelector('.btn');
btn.onclick = Counter;
const clicks = document.querySelector('.clicks');
clicks.id = document.querySelector('clicks');

var a = 0;

function Counter() {
    a += 1;
    clicks.innerHTML = a;
}
<button class="btn">Click</button>
<p>Clicks: <a class="clicks">0</a></p>

If you want to add reset button, you can use this:

const click = document.querySelector('.click');
click.onclick = Counter;
const reset = document.querySelector('.reset');
reset.onclick = resetCounter;
const clicks = document.querySelector('.clicks');
clicks.id = document.querySelector('clicks');

var a = 0;

function Counter() {
    a += 1;
    clicks.innerHTML = a;
}

function resetCounter() {
    a = 0;
    clicks.innerHTML = a;
}
<button class="click">Click</button>
<p>Clicks: <a class="clicks">0</a></p>
<button class="reset">Reset</button>

Comments

1

You should count these requests server-side, either straight from the web server logs or from the code that resolves the ?id=1234 to load the actual content.

Don't count requests coming from the page author that you gave the ID to, assuming you have some way to tell (a login, a cookie, an IP address) -- this part would be easier from your code rather than the server logs.

Comments

1

You can count all clicks on a page's links with this script:

// This variable contains the number of clicks corresponding to the linked URLs
var clickCount = {}
// List of all a tags
,   aList = document.getElementsByTagName('a')
// Function called every time a link is clicked on
,   clickCounter = function()
    {
        clickCount[this.href] = clickCount[this.href] ? clickCount[this.href]+1 : 1;
    }
;
// The event is attached to every link having a "href" attribute
for (var i=0 ; i<aList.length, a=aList[i] ; i++)
{
    if (this.href)
    {
        a.onclick = clickCounter;
    }
}
// This example uses jQuery to send the data to a PHP script
// A POST request is sent just before the window is closed
onbeforeunload = function()
{
    $.post('/tracking.php', clickCount);
}

PS: I don't worry about anchor links, since their tracking may have some interest of its own. If you do, just test if a.href contains location.href+'#' in the for loop.

2 Comments

You need to go up the DOM looking for an A since the click might be on a child of an A. Also, it might be better to look in document.links as anchors are also A elements but not links.
Thank you for the document.links idea! This is also achieavable with getElementsByTagName if we test the href attribute; but anchor links are not something I worry about, since clicks on them may have some informative value too.
1
<script type="text/javascript">

var clicks = 0;
function linkClick() {
    document.getElementById('clicked').value = ++clicks;
}

document.write('<a href="#" onclick="linkClick()">Click Me!</a>');

You have clicked the link times.

Comments

0

Presumably you are trying to see how many links on a page a user has clicked on in order to see which ones they've visited. That is an unreliable strategy since users can visit links many different ways without clicking on them (context menu, drag to new tab, copy link location, etc.).

If you want to know how many links they've clicked on in the current page, the answer is zero since if they click on a link they should go to another page. If you are using a listener to prevent navigation, then the same listener can also count clicks.

Comments

0

Here's a simple click counter with a limiting factor of 200ms between clicks. In this example I've made it so after 3 subsequent clicks something will happen:

var onClick = (function(){
  var count = 0, timer;
  return function(){
    count++;
    clearTimeout(timer);
    timer = setTimeout(function(){count = 0}, 200);
    // do whatever after 3 clicks
    if( count > 2 )
      document.body.classList.toggle('mode');
  }
})();

document.body.addEventListener("click", onClick);
html, body{ height:100%; }

body{ 
  font:20px Arial; 
  text-align:center; 
  padding:20px; 
  background:#EFDCE8;
  transition:.3s;
  -moz-user-select:none;
  -webkit-user-select:none;
}

body.mode{ background:lightgreen; }
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
</head>
<body>
    Click anwhere 3 times
</body>
</html>

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.