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';
}


Related Posts