简体   繁体   中英

How to count clicks with javascript?

Can I count clicks on links with javascript?

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);"

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.

<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.

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.

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.

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>

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>

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM