Google Analytics: track outgoing clicks with jQuery

The script below allows you to track clicks to external links to your website.

In addition, I leave you the code to track PNG image openings and zip file downloads.

jQuery('a').click(function(){
    var linktype = '';
    // Get click href attribut
    var hreflink = jQuery(this).attr('href');
    var myClass = jQuery(this).attr("class");
    
    // Debug
    console.log('Link clicked : ' + hreflink);
    console.log('Class clicked : ' + myClass);

    linktype = hrefType(hreflink);

    // Debug
    console.log('Link type : ' + linktype);

    if( typeof gtag == "undefined" ){
        // Debug
        console.log('GA not loaded');
    }else{
        if(linktype == 'external'){
            gtag ('event', 'clic', {
                'event_category': 'Outlink',
                'event_label': hreflink,
                'transport_type': 'beacon'
              });
        }else if(linktype == 'internal_image'){
            //Debug
            console.log('Click on image');
            gtag ('event', 'clic', {
                'event_category': 'Images',
                'event_label': hreflink,
                'transport_type': 'beacon'
            });
        }else if(linktype == 'internal_download'){
            //Debug
            console.log('Click on file');
            gtag ('event', 'Download', {
                'event_category': hreflink.substr(hreflink.length - 3),
                'event_label': hreflink,
                'transport_type': 'beacon'
            });
        }
    }    
});

function hrefType(link){
    var url = link;
    var sourceString = url.replace('http://','').replace('https://','').replace('www.','').split(/[/?#]/)[0];

    if(sourceString.charAt(0) == ''){
        return "Anchor";
    }

    if(sourceString !== window.location.host){
        return 'external';
    }

    if(sourceString == window.location.host){

        if(link.substr(link.length - 3) == 'png'){
            return 'internal_image';
        }else if(link.substr(link.length - 3) == 'zip'){
            return 'internal_download'
        }

        return 'internal';
    }

    return 'unknow';
}
Categories Uncategorized

Related Posts


Managing virtual machines in a Windows Server Hyper-V cluster

In this tutorial, we will see how to manage your virtual machines in a Hyper-V cluster using the Cluster Manager console. It is also possible to use the following tools to manage virtual machines with

QNAP : volume configuration

Introduction When provisioning a NAS, the first step is to create one or more volumes with the disks installed in it. NAS QNAP offers two types of volumes: Volume based on a pool of disks. Volume on r

OneDrive OnPremise with SharePoint

Presentation OneDrive is Microsoft's tool for storing information in the cloud and having a synchronized copy on your computer. This solution is increasingly used by individuals to save their data, so