Although i’ve become quite well versed in jQuery unfortunately my Javascript is somewhat lacking and I don’t have access to jQuery in this instance, so please no “use jQuery” answers.
Basically Google Analytics enables me to track social clicks as so:
_gaq.push(['_trackSocial', 'facebook', 'like', 'http://domain.com/somepage']);
Now I have various links on my page like so:
<a href="#myfacebook#" track_social="facebook"><img src="facebook_button" /></a>
<a href="#mytwitter#" track_social="twitter"><img src="twitter_button" /></a>
<a href="#mygoogleplus#" track_social="googleplus"><img src="googleplus_button" /></a>
<a href="#mypinterest#" track_social="pinterest"><img src="pinterest_button" /></a>
Now what I would like is to track clicks on each of these and run the Google Analytics code demonstrated above. If I was using jQuery I would do something like this:
$('a[track_social]').click(function(){
_gaq.push(['_trackSocial', $(this).attr('track_social'), 'click', $(this).attr('href')]);
});
But as I said I don’t have access to jQuery so how would I do this using general Javascript?
It doesn’t necessarily have to use the “track_social” attribute, I could put something else in, but it can’t be unique ID’s for every single one as they’ll be appearing in multiple ways throughout the site and multiple times on various pages.
That jQuery can be ported directly to native DOM APIs:
Please note that while this code is fully standards-compliant, it requires JavaScript 1.6 for
forEach(supported in most major browsers, but only in IE 9+), and it requiresaddEventListenerandquerySelectorAll(supported in most major browsers, but only in IE 8+). You could add to this solution if you wanted wider browser support.Supplementary code #1: