$(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