Alan L.
Alan L.

Reputation: 380

Google analytics event tracking integration. Anyone else find a better solution to this?

I haven't tested this in a full production environment, but this little snippet of jQuery seems to be giving me a good way to parse links with customizable class names into an equivalent google analytics events tracking code.

Does this work well for you? Anything I could be doing better here?

jQuery(function(){
        $("a.track").each(function(){
    var obj = $(this); //provide scope
            obj.data("href", obj.attr("href")); 
    obj.data("target", obj.attr("target")); 

    obj.attr({"target": ""}); 
            obj.attr({"href": "#" + obj.data("href") }); 

            obj.click(function(){
                var find = {c: "cat_", a:"action_", l:"label_", d:"data_"}; //define your class prefixes
                var p = {};
                $.each(obj.attr('class').split(/\s+/), function(i,v){
                     $.each(find, function(a, b){
                        if(v.indexOf(b) == 0){ p[a] = v.replace(b, "").replace("__", " "); } //double underscore converted to space
                        });
                    });                
                track(p); Log("tracking...");
                if(obj.data('target') == "_blank"){
        var newWindow = window.open(obj.data("href"), '_blank');
        newWindow.focus();          
        }
        else{ window.location = obj.data("href"); 
        }


        });

            });

        function track(i){
            if(i==undefined || !i["c"] || !i["a"]){Log("Both the 'category' and 'action' are required to track events!"); return;}
            var d = {c: "Category", a:"Action", l:null, d:null}; //set default values
            var p =  $.extend(d, i); //merge function data with defaults                
            _gaq.push(['_trackEvent', p.c, p.a, p.l]);
        }

 function Log(x){try{console.log(x);}catch(e){}}
    });

Upvotes: 2

Views: 491

Answers (2)

spilliton
spilliton

Reputation: 3911

I wrote this thingy and have been using it for all my event tracking:

https://github.com/spilliton/track_that

Upvotes: 1

PetersenDidIt
PetersenDidIt

Reputation: 25620

Seems like a reasonable way to go about it. If it works for you go with it.

Upvotes: 1

Related Questions