Ktown
Ktown

Reputation: 109

Track onclick events

My goal is to store the total amount of clicks on links in a certain page into a variable and recall that variable when the user exits the page. Would this be a correct way of doing it?

window.onunload = function(){
    alert("Total Links Clicked:" + clicks(););
}

var clicks = function(){
    var clickArray = [];
    var getLinks = document.getElementsByTagName(A);

    var clickValue = getLinks.onclick = function() {
    clickArray.push("1");
    }

    var totalClicks = clickArray.length;

    return totalClicks; 
}

Upvotes: 0

Views: 124

Answers (3)

Blender
Blender

Reputation: 298176

Bind a global event listener and just store the count with sessionStorage:

var clicks = 0;

document.addEventListener('click', function(event) {
    if (event.target.nodeName == 'A') {
        window.sessionStorage.setItem('clicks', ++clicks);
    }
}, false);

Upvotes: 0

nnnnnn
nnnnnn

Reputation: 150030

Your code won't work for several reasons:

  • You bind the click handler in clicks() function and don't call clicks() until the page is unloaded, at which point it is too late to handle any clicks. You need to bind the click handler when the page loads.
  • You can't set .onclick on a list of elements, which is what your getLinks variable is given it was set to the result of getElementsByTagName() (get elements not get element).
  • You pass an undeclared variable A to getElementsByTagName(); you should pass the string "a".
  • You have a semicolon inside the alert()'s closing ), which is a syntax error.

You could try something like this:

window.onload = function() {
    var clicks = 0;

    window.onunload = function(){
        alert("Total Links Clicked:" + clicks);
    }

    function clicked() {
         clicks++;
    }

    var getLinks = document.getElementsByTagName("a");    
    for (var i = 0; i < getLinks.length; i++)
        getLinks[i].onclick = clicked;
};

Note that the browser may block an alert() during an unload event, but if you use console.log() instead you can see that clicks had the right value.

Note also that of course a click on a link to another page will cause an unload, so the click count will only be more than 1 if you have links within the current page.

Demo: http://jsfiddle.net/A3bkT/1/

Upvotes: 1

Kyle Emmanuel
Kyle Emmanuel

Reputation: 2221

You can use sessionStorage or localStorage for that.

if(typeof(Storage)!=="undefined")
{
   // store the clicks here
   sessionStorage.numClicks = value;
}

and read more on these two here : http://www.w3schools.com/html/html5_webstorage.asp

Upvotes: 0

Related Questions