Keep in mind these examples REQUIRE the following (for the web page):
- jQuery library loaded.
- Google Analytics "ga.js" asynchronous code loaded.
- Google Analtyics configured for tracking your domain.
- Google Analtyics snippet uses _gaq (not a different variable).
These NEED to occur before any "submit" or "click". There is still a small chance the event will not be tracked.
You will ALSO want to look into adding Google Analytics "e-commerce tracking" when a transaction is completed. There are a few threads on this website and the internet with examples :)
EXAMPLE - track "all" form submits (not just successful ones). Yes this should be attached to the "form" not the "input".
Code:
$(document).ready(function() {
$('form').submit(function(event) {
// Add some code to determine which product is added
var product = 'Product Name + ID';
var _gaq = _gaq || []; // Left to avoid issues if GA not loaded
_gaq.push(['_trackEvent', 'addtobasket', 'product added', product]);
});
});
EXAMPLE - track clicks sending visitors to external resources (other websites such as social media):
Code:
jQuery(document).ready(function() {
var re = new RegExp('^http(:?s)?://' + document.location.hostname);
$('body').on('click', 'a', (function() {
var href = $(this).attr('href');
if(!re.test(href)) {
var _gaq = _gaq || []; // Left to avoid issues if GA not loaded
_gaq.push(['_trackEvent', 'external', 'link', href]);
}
}));
});
Bookmarks