Search code examples
javascripthtmlgoogle-analyticsanalyticsgoogle-analytics-api

Google analytics click event tracking using gtag and conditional/triggers?


Is it possible to track events using triggers without using Tag Manager?

This is the button:

<a href="" onclick="gtag('event', 'accion', { 'event_category' : 'botonDemo', 'event_label' : 'contacto'});">Accedé a una Demo</a>

The website change its url based on the country you selected, for example: https://www.website.com/es/#py is from Paraguay, https://www.website.com/es/#uy is from Uruguay, etc.

So I want to count how many times the button is clicked based on the country. I found out that you can set triggers to activate the event based, for example in this case, if it matches certain url.

I do not have access to Google Tag Manager account to test it, so I was wondering if it is possible to add that logic to the anchor tag itself, but i could not find anything at google developer website.

Thank you


Solution

  • You can get hash in JavaScript:

    var url = window.location.href;
    var hash_val = url.split("#")[1]
    

    Try this example:

    var url = 'https://www.website.com/es/#py';
    var hash_val = url.split("#")[1];
    console.log(hash_val);
    
    // result: py
    

    So you can apply this logic to send event to Google Analytics on click in the link in your page.