JSFiddle - React, Tailwind, and code Playground

(JSON) gaEvents from classnames

by web-nfo.com

HTML

<a href="#" class="gaEvent" target="_blank" rel='{"category":"Test","action":"test","label":"test"}'>Track Event on click</a>
<br>
<a href="#" class="gaPageview " rel="{'url':'http://www.domain.com/test/'}">Track Pageview on click</a>

JavaScript

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-XXXX-Y', {
    'cookieDomain': 'none'
});



var j = {};

$(document).ready(function()
{
    $('.gaEvent').click(function(e){
        e.preventDefault();
        
        var $this = $(this);
        var target = $this.attr('target');
        var href = $this.attr('href');
        var json = $this.attr('rel');
        
        try {
            json = JSON.parse( json );
            j=json;
        } catch (e) {
            json = false;
        }
        
        if(json === false) {
            if(typeof target !== "undefined" && target == "_blank") {
                window.open(href);
            } else {
                window.location.href = href;
            }
        } else {
            console.log(json.cat);
            var eventCategory = (json.category !== "undefined" ? json.category : false);
            var eventAction = (json.action !== "undefined" ? json.action : false);
            var eventLabel = (json.label !== "undefined" ? json.label : false);
            
            ga('send', {
                'hitType':       'event',    // Required
                'eventCategory': myCategory, // Required
                'eventAction':   myAction,   // Required
                'eventLabel':    myLabel,    // optional
                'eventValue':    myValue,    // optional (number!)
                'hitCallback':   function (){
                    // Google tracking send, continue here...
                    console.log('afterCallback');
                }
            });
        }
    });
    
    $('.gaPageview').click(function(e){
        e.preventDefault();
    });
    
});