Mere Development
Mere Development

Reputation: 2519

Passing a variable to Google Analytics ga and hitCallback

I'm trying to get a load of podcast episode links to send event notifications to Google Analytics. I have the following code:

$('.epdirect').on('click', function(event) {
    event.preventDefault();
    thishref = $(this).attr("href");
    var epfile = querySt($(this).attr("href"),"url");
    ga('send', 'event', 'Downloads', 'epdirect', epfile, {'hitCallback':
        function (thishref) {
                document.location = thishref;
        }
    });
});

Each episode link has the 'epdirect' class added like so:

<a class="epdirect" href="path/to/my.mp3">Ep1: What's it all for?</a>

and when used that code correctly records the event and the episode filename in Analytics, but when it tries to redirect to 'thishref' it fails. On checking, 'thishref' is undefined.

The 'querySt' function just pulls the QS parameters out of the URL so I don't think it's relevant here.

The whole reason I'm using the 'hitCallback' function is to stop the episode loading in before the ga function has successfully recorded the hit. Is my thinking right?

Final code This works now. Thanks to accepted answerer for the missing 'var'.

$('.epdirect').on('click', function(event) {
    event.preventDefault();
    var eppath = $(this).attr("href");
    var epfile = eppath.split('/').pop();
    ga('send', 'event', 'Downloads', 'epdirect', epfile, {'hitCallback': function(){
        document.location = eppath;
    }})
});

Thanks, Ben

Upvotes: 1

Views: 747

Answers (1)

osowskit
osowskit

Reputation: 6344

Shouldn't that be:

var thishref = $(this).attr("href");

Yes - the hitCallback seems like a good choice here. This is a good reference page:

Upvotes: 1

Related Questions