Track Google Analytics from onclick and do not redirect

Viewed 88

I want to track a click from a link. User clicks link and opens in new tab and GA tracks the event. The code I have opens in a new tab and tracks the events. However the first page is also redirect to the pdf. The first page should remain. Any ideas on how I can make this happen?

Here is my code.

js

function waitForLoad(id, callback){
    var timer = setInterval(function(){
        if(document.getElementById(id)){
            clearInterval(timer);
            callback();
        }
    }, 100);
}

    waitForLoad("trackbooks", function(){
    console.log("load successful, you can proceed!!");
    document.getElementById("trackbooks").onclick = function()
    {
       // alert("I got clicked");
        var that=this;_gaq.push(['_trackEvent','Download','PDF',this.href]);setTimeout(function(){location.href=that.href;},200); e.preventDefault(); ;return false; 
    }
});

html

<a id="trackbooks" class="fusion-button button-flat" rel="noopener noreferrer" href="http://testdomain.com/mycool.pdf" target="_blank">Download ></a>
0 Answers
Related