Question

I'm pretty new with JavaScript and jQuery and i'm having a hard time attaching onClick Google Analytics tracking inside an A link in our website redesign using jQuery.

I know that I can just do this:

<a href="#" onClick="_gaq.push(['_trackPageview', 'URL']);">link</a> 

However SharePoint html field deletes the onClick code whenever I put it there so I need a script that does that for me.

So far I have this:

<a class="tracking" href="URL">Read PDF</a>

jQuery(document).ready(function($) {
    $(".tracking").click(function() {
        _gaq.push(['_trackPageview', 'url']);
    });
});

The clicked PDF doesn't show up in the real time analytics page when I checked. So I need something that would ensure that when the link is clicked, it shows up in the Analytics tracker in real time. Can I use a script that adds the onClick tracking event inside the A link.

Please help.

Thanks!

Was it helpful?

Solution

You can generate a page view with the following code:

$(document).ready(function() {
    $(".tracking").click(function() {
        ga('send','pageview','my-pdf-document')
    });
});

You can actually pass even more data. See the official doc here: https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced#send

ga('send', 'pageview', {
  'page': '/my-pdf.pdf',
  'title': 'My PDF Title'
});

UPDATE

You could definitely use your href dynamically like this

ga('send','pageview', $(this).attr('href'));

or even use some HTML-5, you can have your link like this:

<a href="/mypdf.pdf" class="tracking" data-title="mypdf-title">link</a>

and do

ga('send', 'pageview', {
    'page': $(this).attr("href"),
    'title': $(this).data("title")
});

EDIT 2

If you're still using ga.js, you can do it this way then:

_gaq.push(['_trackPageview', $(this).attr('href')]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top