I’m trying to track all links clicked with Google Analytics as events. So I wrote some jQuery to capture that. I’m just starting with jQuery, so I don’t know if I’m doing it the most efficient way so I’d like some feedback or suggestions as to how to improve the code. The simpler and faster it is, the better, as it is tracking analytics.
EDIT: Here’s the latest code. I can’t figure out why the last button and 3rd to last return undefined values.
http://jsfiddle.net/uqj88/
Here’s the code that I have so far:
$(document).ready( function() {
var pageURL = window.location.pathname;
var linkText;
$('a').click(function (e) {
if ($(this).text() != ""){
linkText = $(this).text();
}
else if (($(this).text() === "") && ($(this).children("img") != "") && ($(this).children("img").attr("alt") != "")) {
linkText = $(this).children("img").attr("alt");
}
else if (($(this).text() === "") && ($(this).children("img") != "") && ($(this).children("img").attr("alt") === "")) {
linkText = $(this).children("img").attr("src").split("/").pop();
}
_gaq.push(['_trackEvent', pageURL, 'click', linkText]);
if (($(this).attr('target') != '_blank') || ($(this).attr('target') != '#')) {
e.preventDefault();
setTimeout('document.location = "' + $(this).attr('href') + '"', 150);
}
});
$('button').click(function () {
linkText = $(this).text();
_gaq.push(['_trackEvent', pageURL, 'click', linkText]);
});
$("input[type='submit']").click(function () {
if ($(this).attr("value") != ""){
linkText = $(this).attr("value");
}
else if (($(this).attr("value") === "") && ($(this).prop("id") != "")) {
linkText = $(this).prop("id");
}
else if (($(this).attr("value") === "") && ($(this).prop("class") != "")) {
linkText = $(this).prop("class");
}
else {
linkText = "button";
}
_gaq.push(['_trackEvent', pageURL, 'click', linkText]);
});
});
I fixed your example. I believe that in newer versions of jQuery (like 1.7+), it is recommended that you not use the
attrmethod. I tested that by using thepropmethod and it now works: http://jsfiddle.net/shanabus/uqj88/3/Also, I know this was sample code but it seemed strange that you used the
vardeclaration before each use oflinkText, I think that messes up the scope of the variable a bit.Hope this helps!