Domanda

I am trying to track comments on blog posts via Google Universal Analytics. I want the label to pick up the name of the blog post so I'm using jQuery to fire the event.

So far I have the following code (which is based on code I used for other websites and work fine) - obviously I must have overlooked something as it is not working:

$(document).ready(function(){
   $('#commentform').submit(function(){
     var postname = $('h2.post-title').text();
     ga('send', 'event', 'Engagement', 'Comment', postname, 5);

   });
});

Any thoughts?

(Sorry I would link to the blog but it is not live yet)

Thanks

È stato utile?

Soluzione

$(document).ready(function(){
$('#commentform').submit(function(){
var postname = $('h2.post-title').text();
ga('send', 'event', 'Engagement', 'Comment', postname, 5);
});
});

First of all. This code assigns the text of a h2 tag with class post-title found in the document. A way more reliable way to get the title of the post would be an id.

Secondly, it may not work, because the form is submited before the Google Analitycs code fires. So you should stop the default behaviour and submit the form after the analitycs finishes sending it's data. (See: https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced#hitCallback)

$( document ).ready( function() {
    $( document ).on( 'submit', 'form#commentform', function( e ) {
        var postname = $( '#post-title' ).text();
        ga( 'send', {
            'hitType': 'event',
            'eventCategory': 'Engagement',
            'eventAction': 'Comment',
            'eventLabel': postname,
            'eventValue': 5,
            'hitCallback': function() {
                //now you can submit the form
                //$('#commentform').off('submit').trigger('submit');
                $('#commentform').off('submit'); //unbind the event
                $('#commentform')[0].submit(); //fire DOM element event, not jQuery event
            }
        });
        return false;
    });
});

Edit: I just realised the code from hitCallback might not work. The revised version should call the event of the DOM element and in result - send the form.

Edit2: Corrected the event binding in case the form doesn't exist when document.ready() is fired

Altri suggerimenti

Hard to tell without looking at an actual page, but likely the browser is redirecting to the form's submission before ga's network call is made. You'd need a way to wait for ga to finish, then finish submitting the form.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top